import { useEffect, useState } from 'react'
import { companyList, companyCreate, companyUpdate, companyDelete } from '../../../api/uiws'
import { PageHeader, SearchBar, Button, Modal, FormField, Input, Spinner, Pagination, YnBadge, DataGrid, type Column } from '../../../components/uiws/ui'
import AdminGate from './AdminGate'

/**
 * 2.4 거래처 관리 — /api/system/companies. 목록(PageResponse)/검색/등록/수정/다중삭제(본문 ids).
 * RBAC 변경 ADMIN/MANAGER(403 + AdminGate). 색상 토큰만.
 */
type Company = { companyId: string; companyNm: string; bizNo: string; useYn: string }
const empty: Company = { companyId: '', companyNm: '', bizNo: '', useYn: 'Y' }
const PSIZE = 20

function friendlyError(e: any): string {
  if (e?.response?.status === 403) return '권한이 없습니다 (관리자 전용).'
  if (e?.response?.status === 409) return '이미 존재하는 거래처입니다.'
  return e?.response?.data?.message || '요청을 처리하지 못했습니다.'
}

export default function CompanyManagement() {
  const [rows, setRows] = useState<Company[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(0)
  const [kw, setKw] = useState('')
  const [loading, setLoading] = useState(false)
  const [sel, setSel] = useState<Set<string>>(new Set())
  const [open, setOpen] = useState(false)
  const [editing, setEditing] = useState(false)
  const [form, setForm] = useState<Company>(empty)
  const [err, setErr] = useState('')

  async function load(p = page, keyword = kw) {
    setLoading(true)
    try {
      const res = await companyList({ keyword: keyword || undefined, page: p, size: PSIZE })
      setRows(res.data?.data?.content || [])
      setTotal(res.data?.data?.total || 0)
      setSel(new Set())
    } catch { setRows([]); setTotal(0) } finally { setLoading(false) }
  }
  useEffect(() => { load(0, '') }, [])

  function openCreate() { setForm(empty); setEditing(false); setErr(''); setOpen(true) }
  function openEdit(c: Company) { setForm({ ...c }); setEditing(true); setErr(''); setOpen(true) }

  async function save() {
    setErr('')
    if (!form.companyNm.trim()) { setErr('거래처명은 필수입니다.'); return }
    try {
      if (editing) await companyUpdate(form.companyId, form)
      else await companyCreate(form)
      setOpen(false); load()
    } catch (e) { setErr(friendlyError(e)) }
  }
  async function removeSelected() {
    if (sel.size === 0) return
    if (!confirm(`선택한 ${sel.size}개 거래처를 삭제할까요?`)) return
    try { await companyDelete([...sel]); load() } catch (e) { alert(friendlyError(e)) }
  }

  const toggle = (id: string) => setSel(p => { const n = new Set(p); n.has(id) ? n.delete(id) : n.add(id); return n })
  const totalPages = Math.max(1, Math.ceil(total / PSIZE))

  const columns: Column<Company & Record<string, unknown>>[] = [
    { key: 'sel', header: '', width: 36, render: r => (
      <input type="checkbox" checked={sel.has(r.companyId)} onChange={() => toggle(r.companyId)} onClick={e => e.stopPropagation()} />
    ) },
    { key: 'companyId', header: '거래처 ID', render: r => <span className="font-mono">{r.companyId}</span> },
    { key: 'companyNm', header: '거래처명' },
    { key: 'bizNo', header: '사업자번호' },
    { key: 'useYn', header: '사용', width: 80, render: r => <YnBadge yn={r.useYn} yes="사용" no="미사용" /> },
  ]

  return (
    <AdminGate>
      <div className="uiws-scope">
        <PageHeader title="거래처 관리" subtitle="거래처(협력사) 마스터"
          actions={<>
            <Button variant="danger" onClick={removeSelected} disabled={sel.size === 0}>삭제 ({sel.size})</Button>
            <Button onClick={openCreate}>거래처 추가</Button>
          </>} />

        <SearchBar>
          <Input value={kw} onChange={setKw} placeholder="거래처명/사업자번호 검색" style={{ flex: 1, minWidth: 220 }} />
          <Button onClick={() => { setPage(0); load(0, kw) }}>검색</Button>
        </SearchBar>

        {loading ? <Spinner /> : (
          <>
            <DataGrid columns={columns} rows={rows as (Company & Record<string, unknown>)[]} rowKey={r => r.companyId}
              onRowClick={r => openEdit(r)} empty="등록된 거래처가 없습니다." />
            <Pagination page={page} totalPages={totalPages} onChange={p => { setPage(p); load(p) }} />
          </>
        )}

        {open && (
          <Modal title={editing ? '거래처 수정' : '거래처 추가'} onClose={() => setOpen(false)}>
            <FormField label="거래처 ID"><Input value={form.companyId} onChange={v => setForm({ ...form, companyId: v })} placeholder="비우면 자동 생성" style={{ width: '100%' }} /></FormField>
            <FormField label="거래처명"><Input value={form.companyNm} onChange={v => setForm({ ...form, companyNm: v })} style={{ width: '100%' }} /></FormField>
            <FormField label="사업자번호"><Input value={form.bizNo} onChange={v => setForm({ ...form, bizNo: v })} style={{ width: '100%' }} /></FormField>
            <FormField label="사용 여부"><Input value={form.useYn} onChange={v => setForm({ ...form, useYn: v })} placeholder="Y / N" /></FormField>
            {err && <p className="text-xs" style={{ color: 'var(--uiws-danger)' }}>{err}</p>}
            <div className="flex justify-end gap-2 pt-2">
              <Button variant="ghost" onClick={() => setOpen(false)}>취소</Button>
              <Button onClick={save}>저장</Button>
            </div>
          </Modal>
        )}
      </div>
    </AdminGate>
  )
}
