import { useState, type FormEvent } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Pencil, Plus, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import { PageHeader } from '@/components/PageHeader'
import { DataTable, Pagination, type Column } from '@/components/DataTable'
import { PermissionGuard } from '@/components/PermissionGuard'
import { Button } from '@/components/ui/Button'
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 { Dialog } from '@/components/ui/Dialog'
import { api } from '@/lib/api'
import { getErrorMessage } from '@/lib/apiError'
import { MenuKeys } from '@/lib/menuKeys'
import type { Department, Paged } from '@/types/master'

type FormState = { id?: string; code: string; name: string; parentId: string; note: string }
const emptyForm: FormState = { code: '', name: '', parentId: '', note: '' }

export function DepartmentsPage() {
  const qc = useQueryClient()
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [sortBy, setSortBy] = useState<string | undefined>()
  const [sortDesc, setSortDesc] = useState(true)
  const [open, setOpen] = useState(false)
  const [form, setForm] = useState<FormState>(emptyForm)
  const isEdit = !!form.id

  const list = useQuery({
    queryKey: ['departments', { page, search, sortBy, sortDesc }],
    queryFn: async () => {
      const res = await api.get<Paged<Department>>('/departments', {
        params: { page, pageSize: 20, search: search || undefined, sortBy, sortDesc },
      })
      return res.data
    },
  })

  // Toàn bộ phòng ban (không phân trang) để chọn "Phòng cha" + tra tên phòng cha cho cột bảng.
  const allDepts = useQuery({
    queryKey: ['departments-all'],
    queryFn: async () =>
      (await api.get<Paged<Department>>('/departments', { params: { page: 1, pageSize: 200 } })).data.items,
  })
  const deptNameById = new Map((allDepts.data ?? []).map(d => [d.id, `${d.code} — ${d.name}`]))

  const mutate = useMutation({
    mutationFn: async (d: FormState) => {
      const payload = {
        id: d.id,
        code: d.code,
        name: d.name,
        parentId: d.parentId || null,
        managerUserId: null,
        note: d.note || null,
      }
      if (d.id) await api.put(`/departments/${d.id}`, payload)
      else await api.post('/departments', payload)
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['departments'] })
      toast.success(isEdit ? 'Đã cập nhật phòng ban' : 'Đã thêm phòng ban')
      setOpen(false)
      setForm(emptyForm)
    },
    onError: err => toast.error(getErrorMessage(err)),
  })

  const remove = useMutation({
    mutationFn: (id: string) => api.delete(`/departments/${id}`),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['departments'] })
      toast.success('Đã xóa')
    },
    onError: err => toast.error(getErrorMessage(err)),
  })

  const columns: Column<Department>[] = [
    { key: 'code', header: 'Mã', sortable: true, render: d => <span className="font-mono text-xs">{d.code}</span>, width: 'w-32' },
    { key: 'name', header: 'Tên phòng ban', sortable: true, render: d => d.name },
    { key: 'parentId', header: 'Thuộc', render: d => (d.parentId ? deptNameById.get(d.parentId) ?? '—' : '—') },
    { key: 'note', header: 'Ghi chú', render: d => d.note ?? '—' },
    {
      key: 'actions',
      header: '',
      align: 'right',
      width: 'w-28',
      render: d => (
        <div className="flex justify-end gap-1">
          <PermissionGuard menuKey={MenuKeys.Departments} action="Update">
            <Button size="sm" variant="ghost" onClick={() => {
              setForm({ id: d.id, code: d.code, name: d.name, parentId: d.parentId ?? '', note: d.note ?? '' })
              setOpen(true)
            }}>
              <Pencil className="h-3.5 w-3.5" />
            </Button>
          </PermissionGuard>
          <PermissionGuard menuKey={MenuKeys.Departments} action="Delete">
            <Button size="sm" variant="ghost" onClick={() => {
              if (confirm(`Xóa phòng ban "${d.name}"?`)) remove.mutate(d.id)
            }}>
              <Trash2 className="h-3.5 w-3.5 text-red-500" />
            </Button>
          </PermissionGuard>
        </div>
      ),
    },
  ]

  return (
    <div className="p-6">
      <PageHeader
        title="Phòng ban"
        actions={
          <PermissionGuard menuKey={MenuKeys.Departments} action="Create">
            <Button onClick={() => { setForm(emptyForm); setOpen(true) }}>
              <Plus className="h-4 w-4" />
              Thêm phòng ban
            </Button>
          </PermissionGuard>
        }
      />

      <div className="mb-3 flex gap-2">
        <Input
          placeholder="Tìm…"
          value={search}
          onChange={e => { setSearch(e.target.value); setPage(1) }}
          className="max-w-sm"
        />
      </div>

      <DataTable
        columns={columns}
        rows={list.data?.items ?? []}
        getRowKey={d => d.id}
        isLoading={list.isLoading}
        sortBy={sortBy}
        sortDesc={sortDesc}
        onSortChange={(k, desc) => { setSortBy(k); setSortDesc(desc) }}
      />
      <Pagination page={page} pageSize={20} total={list.data?.total ?? 0} onChange={setPage} />

      <Dialog
        open={open}
        onClose={() => setOpen(false)}
        title={isEdit ? 'Sửa phòng ban' : 'Thêm phòng ban mới'}
        footer={
          <>
            <Button variant="outline" onClick={() => setOpen(false)}>Hủy</Button>
            <Button onClick={(e: FormEvent) => { e.preventDefault(); mutate.mutate(form) }} disabled={mutate.isPending}>
              {mutate.isPending ? 'Đang lưu…' : 'Lưu'}
            </Button>
          </>
        }
      >
        <form className="space-y-4" onSubmit={e => { e.preventDefault(); mutate.mutate(form) }}>
          <div className="space-y-1.5">
            <Label>Mã phòng ban *</Label>
            <Input value={form.code} onChange={e => setForm({ ...form, code: e.target.value })} required />
          </div>
          <div className="space-y-1.5">
            <Label>Tên phòng ban *</Label>
            <Input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required />
          </div>
          <div className="space-y-1.5">
            <Label>Phòng cha (Thuộc khối/phòng)</Label>
            <Select value={form.parentId} onChange={e => setForm({ ...form, parentId: e.target.value })}>
              <option value="">— Không có (cấp gốc) —</option>
              {(allDepts.data ?? [])
                .filter(d => d.id !== form.id)
                .map(d => (
                  <option key={d.id} value={d.id}>{d.code} — {d.name}</option>
                ))}
            </Select>
          </div>
          <div className="space-y-1.5">
            <Label>Ghi chú</Label>
            <Textarea rows={3} value={form.note} onChange={e => setForm({ ...form, note: e.target.value })} />
          </div>
        </form>
      </Dialog>
    </div>
  )
}
