import { useEffect, useState } from 'react'
import { roleList, roleCreate, roleUpdate, roleDelete } 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.1 권한(Role) 관리 — /api/system/roles. 목록(PageResponse)·검색·등록·수정·다중삭제.
 * RBAC: 조회 인증, 변경 ADMIN/MANAGER(백엔드 403 + AdminGate 이중 방어). 색상 토큰만 사용.
 */
type Role = { roleId: string; roleNm: string; roleDesc: string; useYn: string }
const empty: Role = { roleId: '', roleNm: '', roleDesc: '', 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 RoleManagement() {
  const [rows, setRows] = useState<Role[]>([])
  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<Role>(empty)
  const [err, setErr] = useState('')

  async function load(p = page, keyword = kw) {
    setLoading(true)
    try {
      const res = await roleList({ 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(r: Role) { setForm({ ...r }); setEditing(true); setErr(''); setOpen(true) }

  async function save() {
    setErr('')
    if (!form.roleId.trim() || !form.roleNm.trim()) { setErr('역할 ID와 이름은 필수입니다.'); return }
    try {
      if (editing) await roleUpdate(form.roleId, form)
      else await roleCreate(form)
      setOpen(false); load()
    } catch (e) { setErr(friendlyError(e)) }
  }

  async function removeSelected() {
    if (sel.size === 0) return
    if (!confirm(`선택한 ${sel.size}개 역할을 삭제할까요?`)) return
    try { await roleDelete([...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<Role & Record<string, unknown>>[] = [
    { key: 'sel', header: '', width: 36, render: r => (
      <input type="checkbox" checked={sel.has(r.roleId)} onChange={() => toggle(r.roleId)} onClick={e => e.stopPropagation()} />
    ) },
    { key: 'roleId', header: '역할 ID', render: r => <span className="font-mono">{r.roleId}</span> },
    { key: 'roleNm', header: '이름' },
    { key: 'roleDesc', header: '설명' },
    { key: 'useYn', header: '사용', width: 80, render: r => <YnBadge yn={r.useYn} yes="사용" no="미사용" /> },
  ]

  return (
    <AdminGate>
      <div className="uiws-scope">
        <PageHeader title="역할/권한 관리" subtitle="시스템 권한(Role) 정의 — RBAC"
          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 (Role & Record<string, unknown>)[]} rowKey={r => r.roleId}
              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.roleId} onChange={v => setForm({ ...form, roleId: v })} placeholder="예: AUDITOR" style={{ width: '100%' }} />
            </FormField>
            <FormField label="이름"><Input value={form.roleNm} onChange={v => setForm({ ...form, roleNm: v })} placeholder="예: 감사자" style={{ width: '100%' }} /></FormField>
            <FormField label="설명"><Input value={form.roleDesc} onChange={v => setForm({ ...form, roleDesc: v })} style={{ width: '100%' }} /></FormField>
            <FormField label="사용 여부"><Input value={form.useYn} onChange={v => setForm({ ...form, useYn: v })} placeholder="Y / N" style={{ width: '100%' }} /></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>
  )
}
