import { useEffect, useState } from 'react'
import { MessageSquareWarning, Check, X, Trash2, ShieldAlert, Sparkles, Inbox, Link2 } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Modal, Empty, Card } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getUgc, getUgcQueue, moderateUgc, getReviewSummary, deleteUgc } from '../api/client'

const UGC_TYPES = ['', 'REVIEW', 'COMMENT', 'POST', 'INQUIRY']
const MOD_STATUS = ['', 'PENDING', 'APPROVED', 'REJECTED']

// AI 위험도 배지
function RiskBadge({ risk }: { risk?: number }) {
  if (risk == null) return null
  const pct = Math.round(risk * 100)
  const cls = risk >= 0.7 ? 'bg-rose-500/15 text-rose-400 border-rose-500/30'
    : risk >= 0.3 ? 'bg-amber-500/15 text-amber-400 border-amber-500/30'
    : 'bg-emerald-500/15 text-emerald-400 border-emerald-500/30'
  return <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs border ${cls}`}><ShieldAlert size={11} /> 위험 {pct}%</span>
}

export default function Ugc() {
  const [queueMode, setQueueMode] = useState(true)
  const [ugcType, setUgcType] = useState('')
  const [moderationStatus, setModerationStatus] = useState('')
  const [list, setList] = useState<any[]>([])
  const [reject, setReject] = useState<any>(null)
  const [reason, setReason] = useState('')
  const [summary, setSummary] = useState<{ ref: string; data: any } | null>(null)
  const writable = canWrite()

  const load = () => {
    const p = queueMode ? getUgcQueue() : getUgc({ ugcType, moderationStatus })
    p.then(d => setList(d || [])).catch(() => setList([]))
  }
  useEffect(() => { load() }, [queueMode, ugcType, moderationStatus])

  const approve = async (id: number) => { await moderateUgc(id, 'APPROVED'); load() }
  const doReject = async () => { await moderateUgc(reject.id, 'REJECTED', reason); setReject(null); setReason(''); load() }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteUgc(id); load() }
  const showSummary = async (ref: string) => { const d = await getReviewSummary(ref); setSummary({ ref, data: d }) }

  return (
    <div>
      <PageHeader title="UGC 모더레이션" subtitle="리뷰 · 댓글 · 게시글 · 문의 — AI 위험도 자동 분류"
        actions={<div className="flex gap-2">
          <Btn variant={queueMode ? 'primary' : 'ghost'} onClick={() => setQueueMode(true)}><Inbox size={15} /> 대기 큐</Btn>
          <Btn variant={!queueMode ? 'primary' : 'ghost'} onClick={() => setQueueMode(false)}>전체</Btn>
        </div>} />

      {!queueMode && (
        <div className="flex flex-wrap items-center gap-2 mb-4">
          <select className="inp w-36" value={ugcType} onChange={e => setUgcType(e.target.value)}>
            {UGC_TYPES.map(t => <option key={t} value={t}>{t || '전체 유형'}</option>)}
          </select>
          <select className="inp w-36" value={moderationStatus} onChange={e => setModerationStatus(e.target.value)}>
            {MOD_STATUS.map(t => <option key={t} value={t}>{t || '전체 상태'}</option>)}
          </select>
        </div>
      )}

      {list.length === 0 ? <Empty msg={queueMode ? '검토 대기 항목이 없습니다.' : 'UGC가 없습니다.'} /> : (
        <div className="space-y-3">
          {list.map(u => (
            <div key={u.id} className="bg-card border border-edge rounded-xl p-4">
              <div className="flex items-start justify-between gap-4">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap mb-1.5">
                    <span className="text-xs font-semibold text-brand">{u.ugcType}</span>
                    <StatusBadge status={u.moderationStatus} />
                    <RiskBadge risk={u.aiRisk} />
                    {u.sentiment && <StatusBadge status={u.sentiment} />}
                    {u.rating != null && <span className="text-xs text-amber-400">★ {u.rating}</span>}
                    {u.itsmSrId && <span className="text-[11px] text-sky-400 flex items-center gap-0.5"><Link2 size={11} /> SR #{u.itsmSrId}</span>}
                  </div>
                  <p className="text-sm text-slate-200">{u.body}</p>
                  <div className="text-[11px] text-slate-500 mt-1.5">
                    {u.authorName || '익명'} · {u.authorEmail || ''} · {u.createdAt ? new Date(u.createdAt).toLocaleString('ko-KR') : ''}
                    {u.targetRef && <> · 대상 {u.targetRef}</>}
                  </div>
                  {u.aiReason && <div className="text-[11px] text-amber-400/80 mt-1">AI: {u.aiReason}</div>}
                </div>
                {writable && (
                  <div className="flex flex-col gap-2 shrink-0">
                    {u.moderationStatus !== 'APPROVED' && <Btn size="sm" onClick={() => approve(u.id)}><Check size={13} /> 승인</Btn>}
                    {u.moderationStatus !== 'REJECTED' && <Btn size="sm" variant="ghost" onClick={() => { setReject(u); setReason('') }}><X size={13} /> 반려</Btn>}
                    {u.ugcType === 'REVIEW' && u.targetRef && <Btn size="sm" variant="ghost" onClick={() => showSummary(u.targetRef)}><Sparkles size={13} /> AI 요약</Btn>}
                    <Btn size="sm" variant="danger" onClick={() => remove(u.id)}><Trash2 size={13} /></Btn>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {reject && (
        <Modal title="UGC 반려" onClose={() => setReject(null)}>
          <p className="text-sm text-slate-300 mb-3 line-clamp-2">{reject.body}</p>
          <textarea className="inp" placeholder="반려 사유 (선택)" value={reason} onChange={e => setReason(e.target.value)} />
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setReject(null)}>취소</Btn>
            <Btn variant="danger" onClick={doReject}>반려</Btn>
          </div>
        </Modal>
      )}

      {summary && (
        <Modal title={`AI 리뷰 요약 — ${summary.ref}`} onClose={() => setSummary(null)}>
          {summary.data ? (
            <Card>
              <div className="flex items-center gap-2 mb-2">
                <StatusBadge status={summary.data.sentiment} />
                <span className="text-xs text-slate-400">점수 {summary.data.score}</span>
              </div>
              <p className="text-sm text-slate-200">{summary.data.summary}</p>
            </Card>
          ) : <p className="text-slate-500 text-sm">요약 데이터가 없습니다.</p>}
        </Modal>
      )}
    </div>
  )
}
