// PE Workflow admin — Session 16 drastic refactor (Mig 21):
// Flat workflow model. Mỗi step = 1 (Phòng × Cấp + Approvers). Bỏ Phase Select
// (auto-assign ChoDuyet=10 behind scenes). Bỏ InnerSteps sub-section.
import { useMemo, useState, type FormEvent } from 'react'
import { useParams } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { GitBranch, Plus, Trash2, CheckCircle2, Info, History } from 'lucide-react'
import { toast } from 'sonner'
import { PageHeader } from '@/components/PageHeader'
import { Button } from '@/components/ui/Button'
import { Dialog } from '@/components/ui/Dialog'
import { Input } from '@/components/ui/Input'
import { Label } from '@/components/ui/Label'
import { Select } from '@/components/ui/Select'
import { Textarea } from '@/components/ui/Textarea'
import { api } from '@/lib/api'
import { getErrorMessage } from '@/lib/apiError'
import { AVAILABLE_ROLES, RoleLabel, PositionLevel, PositionLevelLabel, PositionLevelShort } from '@/types/users'
import type { Department, Paged } from '@/types/master'

// ===== Types (mirror BE PeWorkflowAdminOverviewDto post-Mig 21) =====

type ApproverDto = { kind: number; assignmentValue: string; displayName: string | null }
type StepDto = {
  id: string
  order: number
  phase: number              // [DEPRECATED] always ChoDuyet=10 for new
  phaseLabel: string
  name: string               // "Phòng A — Cấp 1"
  slaDays: number | null
  departmentId: string | null
  departmentName: string | null
  positionLevel: number | null   // 1=NV, 2=PP, 3=TP
  approvers: ApproverDto[]
}
type DefinitionDto = {
  id: string
  code: string
  version: number
  evaluationType: number
  evaluationTypeLabel: string
  name: string
  description: string | null
  isActive: boolean
  activatedAt: string | null
  createdAt: string
  evaluationsUsingCount: number
  steps: StepDto[]
}
type TypeSummaryDto = {
  evaluationType: number
  evaluationTypeLabel: string
  active: DefinitionDto | null
  history: DefinitionDto[]
}

const PHASE_CHO_DUYET = 10  // Mig 21 — generic intermediate phase

type EditStepApprover = { kind: 1 | 2; assignmentValue: string }
type EditStep = {
  name: string                     // "Phòng A — Cấp 1"
  slaDays: number | null
  departmentId: string | null
  positionLevel: number | null     // 1/2/3
  approvers: EditStepApprover[]
}

function copyFromDefinition(d: DefinitionDto): EditStep[] {
  return d.steps.map(s => ({
    name: s.name,
    slaDays: s.slaDays,
    departmentId: s.departmentId,
    positionLevel: s.positionLevel,
    approvers: s.approvers.map(a => ({ kind: a.kind as 1 | 2, assignmentValue: a.assignmentValue })),
  }))
}

const PE_TYPE_CODE_TO_INT: Record<string, number> = {
  DuyetNcc: 1,
  DuyetNccPhuongAn: 2,
}

export function PeWorkflowsPage() {
  const qc = useQueryClient()
  const { typeCode } = useParams<{ typeCode?: string }>()
  const overview = useQuery({
    queryKey: ['pe-workflow-overview'],
    queryFn: async () => (await api.get<{ types: TypeSummaryDto[] }>('/pe-workflows')).data,
  })

  const selectedTypeInt = typeCode ? PE_TYPE_CODE_TO_INT[typeCode] : null
  const currentType = selectedTypeInt
    ? overview.data?.types.find(t => t.evaluationType === selectedTypeInt)
    : null

  return (
    <div className="p-6">
      <PageHeader
        title={
          <span className="flex items-center gap-2">
            <GitBranch className="h-5 w-5" />
            {currentType ? `Quy trình: ${currentType.evaluationTypeLabel}` : 'Quy trình duyệt NCC (PE)'}
          </span>
        }
        description={
          currentType
            ? 'Mỗi bước = 1 Phòng × Cấp duyệt. Order asc tuần tự. Hết bước = đã duyệt.'
            : 'Chọn loại Duyệt NCC từ menu bên trái để xem + chỉnh quy trình.'
        }
      />

      {overview.isLoading && <div className="text-sm text-slate-500">Đang tải…</div>}

      {overview.data && !currentType && (
        <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
          {overview.data.types.map(t => (
            <div key={t.evaluationType} className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
              <div className="flex items-center justify-between">
                <h3 className="text-sm font-semibold text-slate-800">{t.evaluationTypeLabel}</h3>
                {t.active && (
                  <span className="rounded bg-brand-50 px-2 py-0.5 font-mono text-[10px] font-medium text-brand-700">
                    {t.active.code} v{String(t.active.version).padStart(2, '0')}
                  </span>
                )}
              </div>
              <div className="mt-2 text-xs text-slate-500">
                {t.active
                  ? `${t.active.steps.length} bước · ${t.history.length} version${t.history.length > 1 ? 's' : ''}`
                  : 'Chưa có quy trình'}
              </div>
            </div>
          ))}
        </div>
      )}

      {currentType && <TypePanel type={currentType} onSaved={() => qc.invalidateQueries({ queryKey: ['pe-workflow-overview'] })} />}
    </div>
  )
}

// ===== Per-type panel =====

function TypePanel({ type, onSaved }: { type: TypeSummaryDto; onSaved: () => void }) {
  const [designerOpen, setDesignerOpen] = useState(false)
  const [cloneFrom, setCloneFrom] = useState<DefinitionDto | null>(null)

  return (
    <div className="space-y-4">
      {type.active ? (
        <DefinitionCard def={type.active} isActive onClone={d => { setCloneFrom(d); setDesignerOpen(true) }} />
      ) : (
        <div className="rounded-xl border border-dashed border-slate-300 p-8 text-center text-sm text-slate-500">
          Chưa có quy trình cho loại này. Tạo version đầu tiên bên dưới.
        </div>
      )}

      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-slate-700">Lịch sử versions</h3>
        <Button onClick={() => { setCloneFrom(type.active); setDesignerOpen(true) }}>
          <Plus className="h-4 w-4" />
          Tạo quy trình mới
        </Button>
      </div>

      {type.history.filter(d => !d.isActive).length === 0 && (
        <div className="rounded-md border border-slate-200 bg-slate-50 p-4 text-xs text-slate-500">
          Chưa có version cũ. Khi tạo version mới, version hiện tại tự động archive.
        </div>
      )}

      <div className="space-y-2">
        {type.history
          .filter(d => !d.isActive)
          .map(d => (
            <DefinitionCard key={d.id} def={d} isActive={false} onClone={dd => { setCloneFrom(dd); setDesignerOpen(true) }} />
          ))}
      </div>

      {designerOpen && (
        <PeWorkflowDesigner
          evaluationType={type.evaluationType}
          evaluationTypeLabel={type.evaluationTypeLabel}
          cloneFrom={cloneFrom}
          onClose={() => { setDesignerOpen(false); setCloneFrom(null) }}
          onSaved={() => { setDesignerOpen(false); setCloneFrom(null); onSaved() }}
        />
      )}
    </div>
  )
}

// ===== Definition card (read-only view) =====

function DefinitionCard({ def, isActive, onClone }: { def: DefinitionDto; isActive: boolean; onClone: (d: DefinitionDto) => void }) {
  return (
    <div className={`rounded-xl border bg-white p-5 shadow-sm ${isActive ? 'border-brand-200' : 'border-slate-200'}`}>
      <div className="flex items-start justify-between gap-4">
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <h3 className="text-[15px] font-semibold text-slate-900">{def.name}</h3>
            <span className="rounded bg-slate-100 px-2 py-0.5 font-mono text-[11px] text-slate-600">
              {def.code} v{String(def.version).padStart(2, '0')}
            </span>
            {isActive ? (
              <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-medium text-emerald-700">
                <CheckCircle2 className="h-3 w-3" />
                Đang áp dụng
              </span>
            ) : (
              <span className="inline-flex items-center gap-1 rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-medium text-slate-600">
                <History className="h-3 w-3" />
                Archived · {def.evaluationsUsingCount} phiếu còn chạy
              </span>
            )}
          </div>
          {def.description && <p className="mt-1 text-xs leading-relaxed text-slate-500">{def.description}</p>}

          <ol className="mt-3 space-y-2">
            {def.steps.map(s => (
              <li key={s.id} className="flex items-start gap-3 rounded-lg border border-slate-100 bg-slate-50/30 p-2.5">
                <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-brand-600 text-[11px] font-bold text-white">
                  {s.order}
                </div>
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2 text-sm">
                    <span className="font-medium text-slate-800">{s.name}</span>
                    {s.departmentName && (
                      <span className="rounded bg-emerald-50 px-1.5 py-0.5 text-[10px] font-medium text-emerald-700">
                        {s.departmentName}
                      </span>
                    )}
                    {s.positionLevel != null && (
                      <span className="rounded bg-violet-50 px-1.5 py-0.5 text-[10px] font-medium text-violet-700">
                        {PositionLevelShort[s.positionLevel]}
                      </span>
                    )}
                    {s.slaDays != null && (
                      <span className="rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-700">
                        SLA {s.slaDays}d
                      </span>
                    )}
                  </div>
                  <div className="mt-1 flex flex-wrap gap-1">
                    {s.approvers.length === 0 && s.departmentName == null && (
                      <span className="text-[11px] italic text-slate-400">Chưa cấu hình người duyệt</span>
                    )}
                    {s.approvers.map((a, i) => (
                      <span
                        key={i}
                        className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${
                          a.kind === 1 ? 'bg-brand-50 text-brand-700' : 'bg-violet-50 text-violet-700'
                        }`}
                      >
                        {a.kind === 1 ? 'Role' : 'User'}: {a.displayName ?? a.assignmentValue}
                      </span>
                    ))}
                  </div>
                </div>
              </li>
            ))}
          </ol>
        </div>
        <Button variant="outline" size="sm" onClick={() => onClone(def)}>
          <Plus className="h-3.5 w-3.5" />
          Tạo từ bản này
        </Button>
      </div>
    </div>
  )
}

// ===== Designer dialog =====

function PeWorkflowDesigner({
  evaluationType,
  evaluationTypeLabel,
  cloneFrom,
  onClose,
  onSaved,
}: {
  evaluationType: number
  evaluationTypeLabel: string
  cloneFrom: DefinitionDto | null
  onClose: () => void
  onSaved: () => void
}) {
  const initialSteps: EditStep[] = useMemo(
    () =>
      cloneFrom
        ? copyFromDefinition(cloneFrom)
        : [{ name: 'Phòng 1 — Cấp 1', slaDays: 3, departmentId: null, positionLevel: PositionLevel.NhanVien, approvers: [] }],
    [cloneFrom],
  )

  const defaultCode = evaluationType === 1 ? 'QT-DN-A' : 'QT-DN-B'
  const [code, setCode] = useState(cloneFrom?.code ?? defaultCode)
  const [name, setName] = useState(cloneFrom ? `${cloneFrom.name} (clone)` : `Quy trình ${evaluationTypeLabel}`)
  const [description, setDescription] = useState(cloneFrom?.description ?? '')
  const [steps, setSteps] = useState<EditStep[]>(initialSteps)

  const usersList = useQuery({
    queryKey: ['users-for-approver'],
    queryFn: async () =>
      (await api.get<{ items: { id: string; fullName: string; email: string }[] }>('/users', { params: { page: 1, pageSize: 200 } })).data.items,
  })

  const departmentsList = useQuery({
    queryKey: ['departments-list'],
    queryFn: async () =>
      (await api.get<Paged<Department>>('/departments', { params: { page: 1, pageSize: 200 } })).data.items,
  })

  const save = useMutation({
    mutationFn: async () => {
      await api.post('/pe-workflows', {
        evaluationType,
        code,
        name,
        description: description || null,
        steps: steps.map((s, i) => ({
          order: i + 1,
          phase: PHASE_CHO_DUYET,    // Mig 21 — always ChoDuyet=10 for new definitions
          name: s.name,
          slaDays: s.slaDays,
          departmentId: s.departmentId,
          positionLevel: s.positionLevel,
          approvers: s.approvers,
        })),
      })
    },
    onSuccess: () => {
      toast.success('Đã lưu quy trình mới. Version cũ đã archive.')
      onSaved()
    },
    onError: err => toast.error(getErrorMessage(err)),
  })

  function submit(e: FormEvent) {
    e.preventDefault()
    if (steps.length === 0) {
      toast.error('Phải có ít nhất 1 bước')
      return
    }
    save.mutate()
  }

  return (
    <Dialog
      open
      onClose={onClose}
      title={`Tạo quy trình mới — ${evaluationTypeLabel}`}
      size="lg"
      footer={
        <>
          <Button variant="outline" onClick={onClose}>Hủy</Button>
          <Button onClick={submit} disabled={save.isPending} form="pe-wf-form">
            {save.isPending ? 'Đang lưu…' : 'Lưu + kích hoạt'}
          </Button>
        </>
      }
    >
      <form id="pe-wf-form" onSubmit={submit} className="space-y-4">
        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-1.5">
            <Label>Mã quy trình *</Label>
            <Input value={code} onChange={e => setCode(e.target.value)} required className="font-mono" />
            <div className="text-[11px] text-slate-400">Vd QT-DN-A. Version auto-tăng mỗi lần lưu.</div>
          </div>
          <div className="space-y-1.5">
            <Label>Tên hiển thị *</Label>
            <Input value={name} onChange={e => setName(e.target.value)} required />
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Mô tả</Label>
            <Textarea rows={2} value={description} onChange={e => setDescription(e.target.value)} />
          </div>
        </div>

        <div className="space-y-2 rounded-lg border border-slate-200 p-3">
          <div className="flex items-center justify-between">
            <Label>Các bước duyệt — mỗi bước = 1 Phòng × Cấp ({steps.length})</Label>
            <Button
              type="button"
              size="sm"
              variant="outline"
              onClick={() => setSteps([...steps, {
                name: `Phòng ${steps.length + 1} — Cấp 1`,
                slaDays: 3,
                departmentId: departmentsList.data?.[0]?.id ?? null,
                positionLevel: PositionLevel.NhanVien,
                approvers: [],
              }])}
            >
              <Plus className="h-3.5 w-3.5" />
              Thêm bước
            </Button>
          </div>

          {steps.map((s, idx) => (
            <div key={idx} className="rounded-md border border-slate-200 bg-slate-50/40 p-3">
              <div className="flex items-start gap-2">
                <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-brand-600 text-[11px] font-bold text-white">
                  {idx + 1}
                </div>
                <div className="grid flex-1 grid-cols-4 gap-2">
                  <div className="col-span-2">
                    <Label className="text-[11px]">Tên bước</Label>
                    <Input value={s.name} onChange={e => setSteps(steps.map((x, i) => (i === idx ? { ...x, name: e.target.value } : x)))} />
                  </div>
                  <div>
                    <Label className="text-[11px]">Phòng</Label>
                    <Select
                      value={s.departmentId ?? ''}
                      onChange={e => setSteps(steps.map((x, i) => (i === idx ? { ...x, departmentId: e.target.value || null } : x)))}
                    >
                      <option value="">— Không —</option>
                      {departmentsList.data?.map(d => (
                        <option key={d.id} value={d.id}>{d.name}</option>
                      ))}
                    </Select>
                  </div>
                  <div>
                    <Label className="text-[11px]">Cấp</Label>
                    <Select
                      value={s.positionLevel ?? ''}
                      onChange={e => setSteps(steps.map((x, i) => (i === idx ? { ...x, positionLevel: e.target.value ? Number(e.target.value) : null } : x)))}
                    >
                      <option value="">— Không —</option>
                      <option value={PositionLevel.NhanVien}>{PositionLevelLabel[1]}</option>
                      <option value={PositionLevel.PhoPhong}>{PositionLevelLabel[2]}</option>
                      <option value={PositionLevel.TruongPhong}>{PositionLevelLabel[3]}</option>
                    </Select>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => setSteps(steps.filter((_, i) => i !== idx))}
                  className="flex h-7 w-7 items-center justify-center rounded text-slate-400 hover:bg-red-50 hover:text-red-600"
                  title="Xóa bước"
                >
                  <Trash2 className="h-3.5 w-3.5" />
                </button>
              </div>

              <div className="mt-2 grid grid-cols-2 gap-2 border-t border-slate-200 pt-2">
                <div>
                  <Label className="text-[11px]">SLA (ngày, optional)</Label>
                  <Input
                    type="number"
                    min={0}
                    value={s.slaDays ?? ''}
                    onChange={e =>
                      setSteps(steps.map((x, i) => (i === idx ? { ...x, slaDays: e.target.value ? Number(e.target.value) : null } : x)))
                    }
                  />
                </div>
                <div>
                  <Label className="text-[11px]">Người duyệt explicit (optional — fallback nếu không Phòng+Cấp)</Label>
                  <div className="flex gap-1">
                    <button
                      type="button"
                      onClick={() => setSteps(steps.map((x, i) => (i === idx ? { ...x, approvers: [...x.approvers, { kind: 1, assignmentValue: AVAILABLE_ROLES[1] }] } : x)))}
                      className="rounded bg-brand-50 px-2 py-1 text-[11px] font-medium text-brand-700 hover:bg-brand-100"
                    >
                      + Role
                    </button>
                    <button
                      type="button"
                      onClick={() => setSteps(steps.map((x, i) => (i === idx ? { ...x, approvers: [...x.approvers, { kind: 2, assignmentValue: usersList.data?.[0]?.id ?? '' }] } : x)))}
                      className="rounded bg-violet-50 px-2 py-1 text-[11px] font-medium text-violet-700 hover:bg-violet-100"
                    >
                      + User
                    </button>
                  </div>
                </div>
              </div>

              {s.approvers.length > 0 && (
                <div className="mt-1 space-y-1">
                  {s.approvers.map((a, ai) => (
                    <div key={ai} className="flex items-center gap-1">
                      {a.kind === 1 ? (
                        <Select
                          value={a.assignmentValue}
                          onChange={e =>
                            setSteps(steps.map((x, i) =>
                              i === idx ? { ...x, approvers: x.approvers.map((y, j) => (j === ai ? { ...y, assignmentValue: e.target.value } : y)) } : x,
                            ))
                          }
                          className="h-7 flex-1 text-xs"
                        >
                          {AVAILABLE_ROLES.map(r => (
                            <option key={r} value={r}>Role: {RoleLabel[r] ?? r}</option>
                          ))}
                        </Select>
                      ) : (
                        <Select
                          value={a.assignmentValue}
                          onChange={e =>
                            setSteps(steps.map((x, i) =>
                              i === idx ? { ...x, approvers: x.approvers.map((y, j) => (j === ai ? { ...y, assignmentValue: e.target.value } : y)) } : x,
                            ))
                          }
                          className="h-7 flex-1 text-xs"
                        >
                          {usersList.data?.map(u => (
                            <option key={u.id} value={u.id}>User: {u.fullName} ({u.email})</option>
                          ))}
                        </Select>
                      )}
                      <button
                        type="button"
                        onClick={() =>
                          setSteps(steps.map((x, i) =>
                            i === idx ? { ...x, approvers: x.approvers.filter((_, j) => j !== ai) } : x,
                          ))
                        }
                        className="flex h-6 w-6 items-center justify-center rounded text-slate-400 hover:bg-red-50 hover:text-red-600"
                      >
                        <Trash2 className="h-3 w-3" />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>

        <div className="flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
          <Info className="mt-0.5 h-3.5 w-3.5 shrink-0" />
          <div>
            Mig 21 flat workflow: mỗi bước = 1 Phòng × Cấp. User cùng Phòng + Cấp ≥ step's level → được duyệt (OR-of-many).
            User có CanBypassReview cấp cao hơn cùng dept → skip cấp dưới. Hết bước = phiếu DaDuyet.
          </div>
        </div>
      </form>
    </Dialog>
  )
}
