import { useState, type FormEvent } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { EyeOff, Globe, Pencil, Plus, Trash2, Upload } 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 { PathLink } from '@/components/ui/PathLink'
import { SupplierImportDialog } from '@/components/master/SupplierImportDialog'
import { api } from '@/lib/api'
import { getErrorMessage } from '@/lib/apiError'
import { MenuKeys } from '@/lib/menuKeys'
import {
  SupplierStatusLabel,
  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
  packageCategory: string
  officeAddress: string
  mailingAddress: string
  fax: string
  bankAccount: string
  secondaryBankAccount: string
  legalRepresentative: string
  legalRepTitle: string
  authorizationNote: string
  linkGuq: string
  linkGpkd: string
  linkHsnl: string
  contactTitle: string
  contactPhone: string
  mailRecipient: string
  referralSource: string
  ownerPmh: string
  status: string
}

const emptyForm: FormState = {
  code: '', name: '', type: SupplierType.NhaCungCap,
  taxCode: '', phone: '', email: '', address: '', contactPerson: '', note: '',
  packageCategory: '', officeAddress: '', mailingAddress: '', fax: '',
  bankAccount: '', secondaryBankAccount: '', legalRepresentative: '', legalRepTitle: '',
  authorizationNote: '', linkGuq: '', linkGpkd: '', linkHsnl: '',
  contactTitle: '', contactPhone: '', mailRecipient: '', referralSource: '', ownerPmh: '',
  status: '',
}

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 [importOpen, setImportOpen] = useState(false)
  const [form, setForm] = useState<FormState>(emptyForm)
  const isEdit = !!form.id

  // Bộ lọc công bố: '' = tất cả · 'true' = đã công bố · 'false' = nháp (ẩn)
  const [published, setPublished] = useState('')
  // Dialog công bố: nhập Mã NCC trước khi NCC hiển thị ra ngoài
  const [publishTarget, setPublishTarget] = useState<Supplier | null>(null)
  const [maNcc, setMaNcc] = useState('')

  const list = useQuery({
    queryKey: ['suppliers', { page, search, sortBy, sortDesc, published }],
    queryFn: async () => {
      const res = await api.get<Paged<Supplier>>('/suppliers', {
        params: {
          page,
          pageSize: 20,
          search: search || undefined,
          sortBy,
          sortDesc,
          published: published === '' ? undefined : published === 'true',
        },
      })
      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,
        packageCategory: data.packageCategory || null,
        officeAddress: data.officeAddress || null,
        mailingAddress: data.mailingAddress || null,
        fax: data.fax || null,
        bankAccount: data.bankAccount || null,
        secondaryBankAccount: data.secondaryBankAccount || null,
        legalRepresentative: data.legalRepresentative || null,
        legalRepTitle: data.legalRepTitle || null,
        authorizationNote: data.authorizationNote || null,
        linkGuq: data.linkGuq || null,
        linkGpkd: data.linkGpkd || null,
        linkHsnl: data.linkHsnl || null,
        contactTitle: data.contactTitle || null,
        contactPhone: data.contactPhone || null,
        mailRecipient: data.mailRecipient || null,
        referralSource: data.referralSource || null,
        ownerPmh: data.ownerPmh || null,
        status: data.status ? Number(data.status) : 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)),
  })

  // Công bố / ẩn NCC — KHÔNG qua UpdateSupplier (chỉ đổi Mã NCC + IsPublic).
  const publish = useMutation({
    mutationFn: async ({ id, maNcc, doPublish }: { id: string; maNcc?: string; doPublish: boolean }) =>
      await api.post(`/suppliers/${id}/publish`, { maNcc: maNcc || undefined, publish: doPublish }),
    onSuccess: (_data, vars) => {
      qc.invalidateQueries({ queryKey: ['suppliers'] })
      toast.success(vars.doPublish ? 'Đã công bố NCC' : 'Đã ẩn NCC')
      setPublishTarget(null)
      setMaNcc('')
    },
    onError: err => toast.error(getErrorMessage(err)),
  })

  function openPublish(s: Supplier) {
    setPublishTarget(s)
    setMaNcc(s.code ?? '')
  }

  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 ?? '',
      packageCategory: s.packageCategory ?? '', officeAddress: s.officeAddress ?? '',
      mailingAddress: s.mailingAddress ?? '', fax: s.fax ?? '',
      bankAccount: s.bankAccount ?? '', secondaryBankAccount: s.secondaryBankAccount ?? '',
      legalRepresentative: s.legalRepresentative ?? '', legalRepTitle: s.legalRepTitle ?? '',
      authorizationNote: s.authorizationNote ?? '', linkGuq: s.linkGuq ?? '',
      linkGpkd: s.linkGpkd ?? '', linkHsnl: s.linkHsnl ?? '',
      contactTitle: s.contactTitle ?? '', contactPhone: s.contactPhone ?? '',
      mailRecipient: s.mailRecipient ?? '', referralSource: s.referralSource ?? '',
      ownerPmh: s.ownerPmh ?? '', status: s.status != null ? String(s.status) : '',
    })
    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: 'isPublic',
      header: 'Trạng thái',
      width: 'w-32',
      render: s =>
        s.isPublic ? (
          <span className="inline-flex items-center rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-semibold text-emerald-700 ring-1 ring-inset ring-emerald-600/20">
            Đã công bố
          </span>
        ) : (
          <span className="inline-flex items-center rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-semibold text-slate-600 ring-1 ring-inset ring-slate-500/20">
            Nháp (ẩn)
          </span>
        ),
    },
    {
      key: 'actions',
      header: '',
      align: 'right',
      width: 'w-40',
      render: s => (
        <div className="flex justify-end gap-1">
          <PermissionGuard menuKey={MenuKeys.Suppliers} action="Update">
            {s.isPublic ? (
              <Button
                size="sm"
                variant="ghost"
                title="Ẩn NCC (bỏ công bố)"
                onClick={() => {
                  if (confirm(`Ẩn NCC "${s.name}"? NCC sẽ không hiển thị ra ngoài.`))
                    publish.mutate({ id: s.id, doPublish: false })
                }}
              >
                <EyeOff className="h-3.5 w-3.5 text-slate-500" />
              </Button>
            ) : (
              <Button size="sm" variant="ghost" title="Công bố NCC" onClick={() => openPublish(s)}>
                <Globe className="h-3.5 w-3.5 text-emerald-600" />
              </Button>
            )}
          </PermissionGuard>
          <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={
          <div className="flex items-center gap-2">
            <PermissionGuard menuKey={MenuKeys.Suppliers} action="Update">
              <Button variant="outline" onClick={() => setImportOpen(true)}>
                <Upload className="h-4 w-4" />
                Import Excel NCC
              </Button>
            </PermissionGuard>
            <PermissionGuard menuKey={MenuKeys.Suppliers} action="Create">
              <Button onClick={openNew}>
                <Plus className="h-4 w-4" />
                Thêm NCC
              </Button>
            </PermissionGuard>
          </div>
        }
      />

      <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"
        />
        <Select
          value={published}
          onChange={e => {
            setPublished(e.target.value)
            setPage(1)
          }}
          className="max-w-[190px]"
        >
          <option value="">Tất cả trạng thái</option>
          <option value="true">Đã công bố</option>
          <option value="false">Nháp (ẩn)</option>
        </Select>
      </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>

          <div className="col-span-2 mt-2 border-t pt-3 text-sm font-semibold text-slate-600">
            Định danh
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Gói thầu</Label>
            <Input value={form.packageCategory} onChange={e => setForm({ ...form, packageCategory: e.target.value })} />
          </div>

          <div className="col-span-2 mt-2 border-t pt-3 text-sm font-semibold text-slate-600">
            Pháp lý &amp; Hợp đồng
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Địa chỉ văn phòng</Label>
            <Input value={form.officeAddress} onChange={e => setForm({ ...form, officeAddress: e.target.value })} />
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Địa chỉ gửi thư</Label>
            <Input value={form.mailingAddress} onChange={e => setForm({ ...form, mailingAddress: e.target.value })} />
          </div>
          <div className="space-y-1.5">
            <Label>Fax</Label>
            <Input value={form.fax} onChange={e => setForm({ ...form, fax: e.target.value })} />
          </div>
          <div className="space-y-1.5">
            <Label>Người đại diện pháp luật</Label>
            <Input
              value={form.legalRepresentative}
              onChange={e => setForm({ ...form, legalRepresentative: e.target.value })}
            />
          </div>
          <div className="space-y-1.5">
            <Label>Chức vụ đại diện</Label>
            <Input value={form.legalRepTitle} onChange={e => setForm({ ...form, legalRepTitle: e.target.value })} />
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Số tài khoản ngân hàng</Label>
            <Input value={form.bankAccount} onChange={e => setForm({ ...form, bankAccount: e.target.value })} />
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Số tài khoản phụ</Label>
            <Input
              value={form.secondaryBankAccount}
              onChange={e => setForm({ ...form, secondaryBankAccount: e.target.value })}
            />
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Giấy ủy quyền (ghi chú)</Label>
            <Textarea
              rows={2}
              value={form.authorizationNote}
              onChange={e => setForm({ ...form, authorizationNote: e.target.value })}
            />
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Link GUQ</Label>
            <Input value={form.linkGuq} onChange={e => setForm({ ...form, linkGuq: e.target.value })} />
            {form.linkGuq.trim() && <PathLink path={form.linkGuq} />}
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Link GPKD</Label>
            <Input value={form.linkGpkd} onChange={e => setForm({ ...form, linkGpkd: e.target.value })} />
            {form.linkGpkd.trim() && <PathLink path={form.linkGpkd} />}
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Link HSNL</Label>
            <Input value={form.linkHsnl} onChange={e => setForm({ ...form, linkHsnl: e.target.value })} />
            {form.linkHsnl.trim() && <PathLink path={form.linkHsnl} />}
          </div>

          <div className="col-span-2 mt-2 border-t pt-3 text-sm font-semibold text-slate-600">
            Liên hệ
          </div>
          <div className="space-y-1.5">
            <Label>Chức vụ người liên hệ</Label>
            <Input value={form.contactTitle} onChange={e => setForm({ ...form, contactTitle: e.target.value })} />
          </div>
          <div className="space-y-1.5">
            <Label>SĐT người liên hệ</Label>
            <Input value={form.contactPhone} onChange={e => setForm({ ...form, contactPhone: e.target.value })} />
          </div>
          <div className="col-span-2 space-y-1.5">
            <Label>Người nhận thư / SĐT</Label>
            <Input value={form.mailRecipient} onChange={e => setForm({ ...form, mailRecipient: e.target.value })} />
          </div>
          <div className="space-y-1.5">
            <Label>Nguồn giới thiệu</Label>
            <Input value={form.referralSource} onChange={e => setForm({ ...form, referralSource: e.target.value })} />
          </div>
          <div className="space-y-1.5">
            <Label>Người phụ trách (PMH)</Label>
            <Input value={form.ownerPmh} onChange={e => setForm({ ...form, ownerPmh: e.target.value })} />
          </div>

          <div className="col-span-2 mt-2 border-t pt-3 text-sm font-semibold text-slate-600">
            Tình trạng
          </div>
          <div className="space-y-1.5">
            <Label>Tình trạng hiện tại</Label>
            <Select value={form.status} onChange={e => setForm({ ...form, status: e.target.value })}>
              <option value="">— Chưa phân loại —</option>
              {Object.entries(SupplierStatusLabel).map(([v, l]) => (
                <option key={v} value={v}>
                  {l}
                </option>
              ))}
            </Select>
          </div>
        </form>
      </Dialog>

      <Dialog
        open={publishTarget !== null}
        onClose={() => setPublishTarget(null)}
        title="Công bố nhà cung cấp"
        size="sm"
        footer={
          <>
            <Button variant="outline" onClick={() => setPublishTarget(null)}>
              Hủy
            </Button>
            <Button
              onClick={() =>
                publishTarget && publish.mutate({ id: publishTarget.id, maNcc: maNcc.trim(), doPublish: true })
              }
              disabled={!maNcc.trim() || publish.isPending}
            >
              {publish.isPending ? 'Đang công bố…' : 'Công bố'}
            </Button>
          </>
        }
      >
        <div className="space-y-3">
          <p className="text-sm text-slate-600">
            Nhập <b>Mã NCC</b> để công bố "{publishTarget?.name}". Sau khi công bố, NCC sẽ hiển thị ở các màn chọn
            NCC (duyệt NCC, hợp đồng).
          </p>
          <div className="space-y-1.5">
            <Label>Mã NCC *</Label>
            <Input value={maNcc} onChange={e => setMaNcc(e.target.value)} placeholder="VD: NCC001" autoFocus />
          </div>
          <p className="text-xs text-slate-400">NCC chưa có Mã NCC sẽ ở trạng thái Nháp (ẩn), chưa hiển thị ra ngoài.</p>
        </div>
      </Dialog>

      <SupplierImportDialog open={importOpen} onClose={() => setImportOpen(false)} />
    </div>
  )
}
