import { useEffect, useState } from 'react'
import { UsersRound, Plus, Trash2, Edit3, Sparkles, Search } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, Card } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getMembers, createMember, updateMember, getMemberCrmInsight, deleteMember } from '../api/client'

const SEGMENTS = ['', 'VIP', 'REGULAR', 'NEW', 'DORMANT']
const STATUSES = ['', 'ACTIVE', 'INACTIVE', 'BLOCKED']
const emptyForm = { memberCode: '', name: '', email: '', phone: '', segment: 'NEW', status: 'ACTIVE', crmCustomerId: '' }

export default function Members() {
  const [list, setList] = useState<any[]>([])
  const [segment, setSegment] = useState('')
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [form, setForm] = useState<any>(null)
  const [insight, setInsight] = useState<{ name: string; data: any } | null>(null)
  const writable = canWrite()

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

  // 신규 작성/수정 시에만 원문 입력. 응답은 마스킹된 값만 옴 — 편집은 신규 입력으로 덮어쓰기 방식.
  const openNew = () => setForm({ ...emptyForm })
  const openEdit = (m: any) => setForm({ id: m.id, memberCode: m.memberCode, name: m.name, email: '', phone: '', segment: m.segment, status: m.status, crmCustomerId: m.crmCustomerId || '' })
  const save = async () => {
    const payload: any = { ...form }
    // 빈 PII는 전송 제외 (마스킹 값 덮어쓰기 방지)
    if (!payload.email) delete payload.email
    if (!payload.phone) delete payload.phone
    if (form.id) await updateMember(form.id, payload); else await createMember(payload)
    setForm(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteMember(id); load() }
  const showInsight = async (m: any) => { const d = await getMemberCrmInsight(m.id); setInsight({ name: m.name, data: d }) }

  return (
    <div>
      <PageHeader title="회원" subtitle="회원 관리 · PII 마스킹 · CRM 인사이트 연계"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 회원 추가</Btn>} />

      <div className="flex flex-wrap items-center gap-2 mb-4">
        <div className="relative">
          <Search size={14} className="absolute left-2.5 top-2.5 text-slate-500" />
          <input value={keyword} onChange={e => setKeyword(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} placeholder="이름/코드 검색" className="inp pl-8 w-52" />
        </div>
        <select className="inp w-36" value={segment} onChange={e => setSegment(e.target.value)}>
          {SEGMENTS.map(s => <option key={s} value={s}>{s || '전체 세그먼트'}</option>)}
        </select>
        <select className="inp w-36" value={status} onChange={e => setStatus(e.target.value)}>
          {STATUSES.map(s => <option key={s} value={s}>{s || '전체 상태'}</option>)}
        </select>
        <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-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(m => (
              <tr key={m.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-mono text-xs text-slate-400">{m.memberCode}</td>
                <td className="font-medium flex items-center gap-2"><UsersRound size={14} className="text-brand" />{m.name}</td>
                <td className="text-slate-400 font-mono text-xs">{m.emailEnc || '—'}</td>
                <td className="text-slate-400 font-mono text-xs">{m.phoneEnc || '—'}</td>
                <td><StatusBadge status={m.segment} /></td>
                <td><StatusBadge status={m.status} /></td>
                <td className="px-4"><div className="flex items-center justify-end gap-3">
                  {m.crmCustomerId && <button onClick={() => showInsight(m)} title="CRM 인사이트" className="text-accent hover:text-accent/80"><Sparkles size={15} /></button>}
                  {writable && <button onClick={() => openEdit(m)} className="text-slate-400 hover:text-brand"><Edit3 size={14} /></button>}
                  {writable && <button onClick={() => remove(m.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>}
                </div></td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={7} msg="회원이 없습니다." />}
          </tbody>
        </table>
      </div>

      {form && (
        <Modal title={form.id ? '회원 편집' : '회원 추가'} onClose={() => setForm(null)}>
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <Field label="회원 코드"><input className="inp" value={form.memberCode} onChange={e => setForm({ ...form, memberCode: e.target.value })} /></Field>
              <Field label="이름"><input className="inp" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} /></Field>
            </div>
            <Field label="이메일" hint={form.id ? '변경 시에만 입력 (빈 값은 기존 유지)' : undefined}><input className="inp" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></Field>
            <Field label="전화" hint={form.id ? '변경 시에만 입력 (빈 값은 기존 유지)' : undefined}><input className="inp" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="세그먼트">
                <select className="inp" value={form.segment} onChange={e => setForm({ ...form, segment: e.target.value })}>
                  {SEGMENTS.filter(Boolean).map(s => <option key={s}>{s}</option>)}
                </select>
              </Field>
              <Field label="상태">
                <select className="inp" value={form.status} onChange={e => setForm({ ...form, status: e.target.value })}>
                  {STATUSES.filter(Boolean).map(s => <option key={s}>{s}</option>)}
                </select>
              </Field>
            </div>
            <Field label="CRM 고객 ID"><input className="inp" value={form.crmCustomerId} onChange={e => setForm({ ...form, crmCustomerId: e.target.value })} /></Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setForm(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}

      {insight && (
        <Modal title={`CRM 인사이트 — ${insight.name}`} onClose={() => setInsight(null)}>
          {insight.data ? (
            <Card><pre className="text-xs text-slate-300 whitespace-pre-wrap">{JSON.stringify(insight.data, null, 2)}</pre></Card>
          ) : <p className="text-slate-500 text-sm">CRM 인사이트가 없습니다.</p>}
        </Modal>
      )}
    </div>
  )
}
