import { useEffect, useState } from 'react'
import { Building2, Plus, Trash2, ShieldCheck } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, maskValue } from '../components/ui'
import { canManage } from '../components/rbac'
import { getPartners, createPartner, updatePartner, deletePartner } from '../api/client'

const TYPES = ['', 'SUPPLIER', 'CUSTOMER', 'BOTH']
const STATUSES = ['', 'ACTIVE', 'INACTIVE']
const emptyForm = { partnerCode: '', partnerName: '', partnerType: 'SUPPLIER', contactName: '', contactPhone: '', contactEmail: '', address: '', status: 'ACTIVE' }

export default function Partners() {
  const [list, setList] = useState<any[]>([])
  const [partnerType, setPartnerType] = useState('')
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [editor, setEditor] = useState<any>(null)
  const manageable = canManage()

  const load = () => getPartners({ partnerType, status, keyword }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [partnerType, status])

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  // 편집 시 마스킹된 연락처는 비우고 새로 입력(서버 응답이 이미 마스킹되어 있음)
  const openEdit = (p: any) => setEditor({ ...p, contactPhone: '', contactEmail: '', _new: false })
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createPartner(payload); else await updatePartner(id, payload)
    setEditor(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deletePartner(id); load() }

  return (
    <div>
      <PageHeader title="거래처" subtitle="공급사 · 고객 · 연락처 AES 암호화 저장 · 응답 마스킹 (MANAGER+)"
        actions={manageable && <Btn onClick={openNew}><Plus size={16} /> 거래처</Btn>} />

      <div className="bg-amber-500/5 border border-amber-500/20 text-amber-300/80 text-xs rounded-lg px-3 py-2 mb-4 flex items-center gap-2">
        <ShieldCheck size={14} /> 거래처 연락처(전화·이메일)는 PII로 마스킹되어 표시됩니다. 원문은 저장 시 AES-256-GCM으로 암호화됩니다.
      </div>

      <div className="flex flex-wrap items-center gap-2 mb-4">
        <select className="inp w-36" value={partnerType} onChange={e => setPartnerType(e.target.value)}>{TYPES.map(t => <option key={t} value={t}>{t || '전체 유형'}</option>)}</select>
        <select className="inp w-32" value={status} onChange={e => setStatus(e.target.value)}>{STATUSES.map(t => <option key={t} value={t}>{t || '전체 상태'}</option>)}</select>
        <input value={keyword} onChange={e => setKeyword(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} placeholder="거래처 검색" className="inp w-52" />
        <Btn variant="ghost" onClick={load}>검색</Btn>
      </div>

      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="text-slate-500 text-xs bg-panel">
            <tr><th className="text-left py-3 px-4">코드</th><th className="text-left">거래처명</th><th className="text-left">유형</th><th className="text-left">담당</th><th className="text-left">전화</th><th className="text-left">이메일</th><th className="text-left">상태</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(p => (
              <tr key={p.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium flex items-center gap-1.5"><Building2 size={14} className="text-brand" />{p.partnerCode}</td>
                <td className="text-slate-300">{p.partnerName}</td>
                <td><span className="px-2 py-0.5 rounded bg-brand/15 text-brand text-xs border border-brand/30">{p.partnerType}</span></td>
                <td className="text-slate-400 text-xs">{p.contactName || '-'}</td>
                <td className="text-slate-400 font-mono text-xs">{p.contactPhone ? maskValue(p.contactPhone) : '-'}</td>
                <td className="text-slate-400 font-mono text-xs">{p.contactEmail ? maskValue(p.contactEmail) : '-'}</td>
                <td><StatusBadge status={p.status} /></td>
                <td className="px-4">
                  {manageable && <div className="flex items-center justify-end gap-2">
                    <button onClick={() => openEdit(p)} className="text-xs text-slate-400 hover:text-brand">편집</button>
                    <button onClick={() => remove(p.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>
                  </div>}
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={8} msg="거래처가 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title={editor._new ? '거래처 등록' : '거래처 편집'} onClose={() => setEditor(null)}>
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <Field label="코드"><input className="inp" value={editor.partnerCode} onChange={e => setEditor({ ...editor, partnerCode: e.target.value })} disabled={!editor._new} /></Field>
              <Field label="거래처명"><input className="inp" value={editor.partnerName} onChange={e => setEditor({ ...editor, partnerName: e.target.value })} /></Field>
            </div>
            <Field label="유형">
              <select className="inp" value={editor.partnerType} onChange={e => setEditor({ ...editor, partnerType: e.target.value })}>
                {['SUPPLIER', 'CUSTOMER', 'BOTH'].map(t => <option key={t}>{t}</option>)}
              </select>
            </Field>
            <Field label="담당자"><input className="inp" value={editor.contactName} onChange={e => setEditor({ ...editor, contactName: e.target.value })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="전화 (암호화 저장)" hint={editor._new ? '' : '변경 시에만 입력'}><input className="inp" value={editor.contactPhone} onChange={e => setEditor({ ...editor, contactPhone: e.target.value })} /></Field>
              <Field label="이메일 (암호화 저장)" hint={editor._new ? '' : '변경 시에만 입력'}><input className="inp" value={editor.contactEmail} onChange={e => setEditor({ ...editor, contactEmail: e.target.value })} /></Field>
            </div>
            <Field label="주소"><input className="inp" value={editor.address} onChange={e => setEditor({ ...editor, address: e.target.value })} /></Field>
            {!editor._new && <Field label="상태">
              <select className="inp" value={editor.status} onChange={e => setEditor({ ...editor, status: e.target.value })}>
                {['ACTIVE', 'INACTIVE'].map(s => <option key={s}>{s}</option>)}
              </select>
            </Field>}
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setEditor(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
