import { useEffect, useMemo, useState } from 'react'
import { deptList, createDept, updateDept, deleteDept } from '../../../api/uiws'
import {
  PageHeader, SearchBar, Input, Button, DataGrid, Modal, FormField, Spinner, YnBadge, type Column,
} from '../../../components/uiws/ui'

interface Dept extends Record<string, unknown> {
  deptId: string; deptNm: string; parentDeptId: string | null; sortOrd: number; useYn: string
}

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 [keyword, setKeyword] = useState('')
  const [loading, setLoading] = useState(false)
  const [err, setErr] = useState('')
  const [form, setForm] = useState<{ open: boolean; edit: Dept | null }>({ open: false, edit: null })

  const load = async (kw = '') => {
    setLoading(true); setErr('')
    try { const res = await deptList(kw || undefined); setRows(res.data.data?.content ?? []) }
    catch (e) { setErr(friendlyError(e)) }
    finally { setLoading(false) }
  }
  useEffect(() => { load('') }, [])

  const ordered = useMemo(() => {
    const roots = rows.filter(r => !r.parentDeptId).sort((a, b) => (a.sortOrd ?? 0) - (b.sortOrd ?? 0))
    const out: (Dept & { _depth: number })[] = []
    for (const root of roots) {
      out.push({ ...root, _depth: 0 })
      rows.filter(r => r.parentDeptId === root.deptId)
        .sort((a, b) => (a.sortOrd ?? 0) - (b.sortOrd ?? 0))
        .forEach(c => out.push({ ...c, _depth: 1 }))
    }
    const seen = new Set(out.map(o => o.deptId))
    rows.filter(r => !seen.has(r.deptId)).forEach(m => out.push({ ...m, _depth: 0 }))
    return out
  }, [rows])

  const remove = async (d: Dept) => {
    if (!window.confirm(`부서 '${d.deptNm}' 를 삭제하시겠습니까?`)) return
    try { await deleteDept(d.deptId); await load() } catch (e) { setErr(friendlyError(e)) }
  }

  const columns: Column<Dept & { _depth: number }>[] = [
    {
      key: 'deptNm', header: '부서명',
      render: r => (
        <span style={{ paddingLeft: r._depth * 22 }}>
          {r._depth > 0 && <span style={{ color: 'var(--uiws-text-faint)' }}>└ </span>}
          {r.deptNm} <span style={{ color: 'var(--uiws-text-muted)', fontSize: 12 }}>({r.deptId})</span>
        </span>
      ),
    },
    { key: 'sortOrd', header: '정렬', width: 70, align: 'center' },
    { key: 'useYn', header: '사용', width: 80, align: 'center', render: r => <YnBadge yn={r.useYn} yes="사용" no="미사용" /> },
    { key: 'act', header: '', width: 60, align: 'center', render: r => <Button variant="ghost" onClick={() => remove(r)}>삭제</Button> },
  ]

  return (
    <div className="uiws-scope">
      <PageHeader title="부서 관리" subtitle="시스템관리(권한) · 부서 트리(2-depth) 등록/수정/삭제"
        actions={<Button onClick={() => setForm({ open: true, edit: null })}>+ 부서 등록</Button>} />

      {err && <div style={{ color: 'var(--uiws-danger)', fontSize: 13, marginBottom: 12 }}>{err}</div>}

      <SearchBar>
        <Input value={keyword} onChange={setKeyword} placeholder="부서명 검색" style={{ minWidth: 220 }} />
        <Button variant="ghost" onClick={() => load(keyword)}>검색</Button>
      </SearchBar>

      {loading ? <Spinner /> : (
        <DataGrid columns={columns} rows={ordered} rowKey={r => r.deptId}
          onRowClick={r => setForm({ open: true, edit: r })} empty="등록된 부서가 없습니다." />
      )}

      {form.open && (
        <DeptForm dept={form.edit} parents={rows.filter(r => !r.parentDeptId)}
          onClose={() => setForm({ open: false, edit: null })}
          onSaved={() => { setForm({ open: false, edit: null }); load(keyword) }} />
      )}
    </div>
  )
}

function DeptForm({ dept, parents, onClose, onSaved }: {
  dept: Dept | null; parents: Dept[]; onClose: () => void; onSaved: () => void
}) {
  const editing = !!dept
  const [deptId, setDeptId] = useState(dept?.deptId ?? '')
  const [deptNm, setDeptNm] = useState(dept?.deptNm ?? '')
  const [parentDeptId, setParentDeptId] = useState(dept?.parentDeptId ?? '')
  const [sortOrd, setSortOrd] = useState(String(dept?.sortOrd ?? 0))
  const [useYn, setUseYn] = useState(dept?.useYn ?? 'Y')
  const [err, setErr] = useState('')

  const selStyle = {
    width: '100%', padding: '9px 12px', borderRadius: 8, fontSize: 13,
    background: 'var(--uiws-input-bg)', border: '1px solid var(--uiws-border)', color: 'var(--uiws-text)',
  } as const

  const save = async () => {
    setErr('')
    if (!editing && !deptId.trim()) { setErr('부서ID는 필수입니다.'); return }
    if (!deptNm.trim()) { setErr('부서명은 필수입니다.'); return }
    try {
      const body = { deptId, deptNm, parentDeptId: parentDeptId || null, sortOrd: Number(sortOrd) || 0, useYn }
      editing ? await updateDept(deptId, body) : await createDept(body)
      onSaved()
    } catch (e) { setErr(friendlyError(e)) }
  }

  return (
    <Modal title={editing ? '부서 수정' : '부서 등록'} onClose={onClose}
      footer={<><Button variant="ghost" onClick={onClose}>취소</Button><Button onClick={save}>저장</Button></>}>
      <FormField label="부서ID"><Input value={deptId} onChange={setDeptId} style={{ width: '100%', opacity: editing ? 0.6 : 1 }} /></FormField>
      <FormField label="부서명"><Input value={deptNm} onChange={setDeptNm} style={{ width: '100%' }} /></FormField>
      <FormField label="상위 부서">
        <select value={parentDeptId} onChange={e => setParentDeptId(e.target.value)} style={selStyle}>
          <option value="">(최상위)</option>
          {parents.filter(p => p.deptId !== deptId).map(p => <option key={p.deptId} value={p.deptId}>{p.deptNm} ({p.deptId})</option>)}
        </select>
      </FormField>
      <FormField label="정렬순서"><Input type="number" value={sortOrd} onChange={setSortOrd} style={{ width: '100%' }} /></FormField>
      <FormField label="사용 여부">
        <select value={useYn} onChange={e => setUseYn(e.target.value)} style={selStyle}>
          <option value="Y">사용</option>
          <option value="N">미사용</option>
        </select>
      </FormField>
      {err && <div style={{ color: 'var(--uiws-danger)', fontSize: 13 }}>{err}</div>}
    </Modal>
  )
}
