import { useEffect, useState } from 'react'
import { deptList, deptCreate, deptUpdate, deptDelete } 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.3 부서 관리 — /api/system/depts. 목록(PageResponse)/검색/등록/수정/개별삭제(path /{id}).
 * RBAC 변경 ADMIN/MANAGER(403 + AdminGate). 색상 토큰만.
 */
type Dept = { deptId: string; deptNm: string; parentDeptId: string; sortOrd: number | null; useYn: string }
const empty: Dept = { deptId: '', deptNm: '', parentDeptId: '', sortOrd: null, useYn: 'Y' }
const PSIZE = 20

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

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

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

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

  async function save() {
    setErr('')
    if (!form.deptNm.trim()) { setErr('부서명은 필수입니다.'); return }
    try {
      if (editing) await deptUpdate(form.deptId, form)
      else await deptCreate(form)
      setOpen(false); load()
    } catch (e) { setErr(friendlyError(e)) }
  }
  async function remove(id: string) {
    if (!confirm(`부서 '${id}' 을(를) 삭제할까요?`)) return
    try { await deptDelete(id); load() } catch (e) { alert(friendlyError(e)) }
  }

  const totalPages = Math.max(1, Math.ceil(total / PSIZE))
  const columns: Column<Dept & Record<string, unknown>>[] = [
    { key: 'deptId', header: '부서 ID', render: r => <span className="font-mono">{r.deptId}</span> },
    { key: 'deptNm', header: '부서명' },
    { key: 'parentDeptId', header: '상위 부서' },
    { key: 'sortOrd', header: '순서', width: 60 },
    { key: 'useYn', header: '사용', width: 80, render: r => <YnBadge yn={r.useYn} yes="사용" no="미사용" /> },
    { key: 'act', header: '', width: 64, align: 'right', render: r => (
      <button onClick={e => { e.stopPropagation(); remove(r.deptId) }} className="text-xs" style={{ color: 'var(--uiws-danger)' }}>삭제</button>
    ) },
  ]

  return (
    <AdminGate>
      <div className="uiws-scope">
        <PageHeader title="부서 관리" subtitle="조직 부서 계층/정렬"
          actions={<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 (Dept & Record<string, unknown>)[]} rowKey={r => r.deptId}
              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.deptId} onChange={v => setForm({ ...form, deptId: v })} placeholder="비우면 자동 생성" style={{ width: '100%' }} /></FormField>
            <FormField label="부서명"><Input value={form.deptNm} onChange={v => setForm({ ...form, deptNm: v })} style={{ width: '100%' }} /></FormField>
            <FormField label="상위 부서 ID"><Input value={form.parentDeptId} onChange={v => setForm({ ...form, parentDeptId: v })} style={{ width: '100%' }} /></FormField>
            <FormField label="정렬 순서"><Input type="number" value={String(form.sortOrd ?? '')} onChange={v => setForm({ ...form, sortOrd: v === '' ? null : Number(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>
  )
}
