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 { SupplierType, SupplierTypeLabel, type Paged, type Supplier } from '@/types/master'

type FormState = {
  id?: string
  code: string
  name: string
  type: SupplierType
  taxCode: string
  phone: string
  email: string
  address: string
  contactPerson: string
  note: string
}

const emptyForm: FormState = {
  code: '', name: '', type: SupplierType.NhaCungCap,
  taxCode: '', phone: '', email: '', address: '', contactPerson: '', note: '',
}

export function SuppliersPage() {
  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: ['suppliers', { page, search, sortBy, sortDesc }],
    queryFn: async () => {
      const res = await api.get<Paged<Supplier>>('/suppliers', {
        params: { page, pageSize: 20, search: search || undefined, sortBy, sortDesc },
      })
      return res.data
    },
  })

  const mutate = useMutation({
    mutationFn: async (data: FormState) => {
      const payload = {
        id: data.id,
        code: data.code,
        name: data.name,
        type: Number(data.type),
        taxCode: data.taxCode || null,
        phone: data.phone || null,
        email: data.email || null,
        address: data.address || null,
        contactPerson: data.contactPerson || null,
        note: data.note || null,
      }
      if (data.id) {
        await api.put(`/suppliers/${data.id}`, payload)
      } else {
        await api.post('/suppliers', payload)
      }
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['suppliers'] })
      toast.success(isEdit ? 'Đã cập nhật NCC' : 'Đã thêm NCC')
      setOpen(false)
      setForm(emptyForm)
    },
    onError: err => toast.error(getErrorMessage(err)),
  })

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

  function openNew() {
    setForm(emptyForm)
    setOpen(true)
  }

  function openEdit(s: Supplier) {
    setForm({
      id: s.id, code: s.code, name: s.name, type: s.type,
      taxCode: s.taxCode ?? '', phone: s.phone ?? '', email: s.email ?? '',
      address: s.address ?? '', contactPerson: s.contactPerson ?? '', note: s.note ?? '',
    })
    setOpen(true)
  }

  function submit(e: FormEvent) {
    e.preventDefault()
    mutate.mutate(form)
  }

  const columns: Column<Supplier>[] = [
    { key: 'code', header: 'Mã', sortable: true, render: s => <span className="font-mono text-xs">{s.code}</span>, width: 'w-32' },
    { key: 'name', header: 'Tên NCC', sortable: true, render: s => s.name },
    { key: 'type', header: 'Loại', sortable: true, width: 'w-36', render: s => SupplierTypeLabel[s.type] },
    { key: 'taxCode', header: 'MST', render: s => s.taxCode ?? '—' },
    { key: 'phone', header: 'Điện thoại', render: s => s.phone ?? '—' },
    {
      key: 'actions',
      header: '',
      align: 'right',
      width: 'w-32',
      render: s => (
        <div className="flex justify-end gap-1">
          <PermissionGuard menuKey={MenuKeys.Suppliers} action="Update">
            <Button size="sm" variant="ghost" onClick={() => openEdit(s)}>
              <Pencil className="h-3.5 w-3.5" />
            </Button>
          </PermissionGuard>
          <PermissionGuard menuKey={MenuKeys.Suppliers} action="Delete">
            <Button
              size="sm"
              variant="ghost"
              onClick={() => {
                if (confirm(`Xóa NCC "${s.name}"?`)) remove.mutate(s.id)
              }}
            >
              <Trash2 className="h-3.5 w-3.5 text-red-500" />
            </Button>
          </PermissionGuard>
        </div>
      ),
    },
  ]

  return (
    <div className="p-6">
      <PageHeader
        title="Nhà cung cấp"
        description="Quản lý NCC / Thầu phụ / Tổ đội / Đơn vị dịch vụ / Chủ đầu tư"
        actions={
          <PermissionGuard menuKey={MenuKeys.Suppliers} action="Create">
            <Button onClick={openNew}>
              <Plus className="h-4 w-4" />
              Thêm NCC
            </Button>
          </PermissionGuard>
        }
      />

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

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

      <Dialog
        open={open}
        onClose={() => setOpen(false)}
        title={isEdit ? 'Sửa NCC' : 'Thêm NCC mới'}
        size="lg"
        footer={
          <>
            <Button variant="outline" onClick={() => setOpen(false)}>
              Hủy
            </Button>
            <Button onClick={submit} disabled={mutate.isPending}>
              {mutate.isPending ? 'Đang lưu…' : 'Lưu'}
            </Button>
          </>
        }
      >
        <form onSubmit={submit} className="grid grid-cols-2 gap-4">
          <div className="space-y-1.5">
            <Label>Mã NCC *</Label>
            <Input value={form.code} onChange={e => setForm({ ...form, code: e.target.value })} required />
          </div>
          <div className="space-y-1.5">
            <Label>Loại *</Label>
            <Select value={form.type} onChange={e => setForm({ ...form, type: Number(e.target.value) as SupplierType })}>
              {Object.entries(SupplierTypeLabel).map(([v, l]) => (
                <option key={v} value={v}>
                  {l}
                </option>
              ))}
            </Select>
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Tên đầy đủ *</Label>
            <Input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required />
          </div>
          <div className="space-y-1.5">
            <Label>MST</Label>
            <Input value={form.taxCode} onChange={e => setForm({ ...form, taxCode: e.target.value })} />
          </div>
          <div className="space-y-1.5">
            <Label>Điện thoại</Label>
            <Input value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} />
          </div>
          <div className="space-y-1.5">
            <Label>Email</Label>
            <Input type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
          </div>
          <div className="space-y-1.5">
            <Label>Người liên hệ</Label>
            <Input value={form.contactPerson} onChange={e => setForm({ ...form, contactPerson: e.target.value })} />
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Địa chỉ</Label>
            <Input value={form.address} onChange={e => setForm({ ...form, address: e.target.value })} />
          </div>
          <div className="col-span-2 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>
  )
}
