// AI 답변 피드백 위젯(👍/👎 + 교정). [GUARDiA-ESN]
//   👍/👎 → /api/ai/feedback (로컬 DuckDB + 중앙 guardia-rag 둘 다 기록). 👎 시 교정 입력 노출.
//   PII 마스킹은 서버(LocalLearningStore)에서 수행 — 화면은 원문만 전달.
import { useState } from 'react'
import { ThumbsUp, ThumbsDown, Send } from 'lucide-react'
import { submitAiFeedback } from '../api/adminAiConfig'

interface Props {
  feature: string
  question?: string
  answer?: string
  answerId?: string
  tenantCode?: string
}

export default function AiFeedback({ feature, question, answer, answerId, tenantCode }: Props) {
  const [verdict, setVerdict] = useState<'up' | 'down' | null>(null)
  const [correction, setCorrection] = useState('')
  const [sent, setSent] = useState(false)
  const [busy, setBusy] = useState(false)

  const send = async (v: 'up' | 'down', corr?: string) => {
    setBusy(true)
    try {
      await submitAiFeedback({ feature, question, answer, verdict: v, correction: corr, answerId, tenantCode })
      setSent(true)
    } catch {
      // 무영향 — 피드백 실패는 조용히 흡수(본 기능은 부가).
      setSent(true)
    } finally {
      setBusy(false)
    }
  }

  const onUp = () => { setVerdict('up'); send('up') }
  const onDown = () => { setVerdict('down') }  // 교정 입력 후 전송
  const onSubmitDown = () => send('down', correction.trim() || undefined)

  if (sent) {
    return <div className="mt-2 text-[11px] text-emerald-300">피드백 감사합니다. 학습에 반영됩니다.</div>
  }

  return (
    <div className="mt-3 flex flex-col gap-2">
      <div className="flex items-center gap-2 text-[11px] text-slate-500">
        <span>이 답변이 도움이 되었나요?</span>
        <button
          onClick={onUp}
          disabled={busy}
          className={`p-1.5 rounded border ${verdict === 'up' ? 'bg-emerald-500/15 border-emerald-500/40 text-emerald-300' : 'border-edge text-slate-400 hover:border-emerald-500/50'}`}
          aria-label="도움됨"
        >
          <ThumbsUp size={13} />
        </button>
        <button
          onClick={onDown}
          disabled={busy}
          className={`p-1.5 rounded border ${verdict === 'down' ? 'bg-rose-500/15 border-rose-500/40 text-rose-300' : 'border-edge text-slate-400 hover:border-rose-500/50'}`}
          aria-label="도움안됨"
        >
          <ThumbsDown size={13} />
        </button>
      </div>
      {verdict === 'down' && (
        <div className="flex items-center gap-2">
          <input
            value={correction}
            onChange={e => setCorrection(e.target.value)}
            placeholder="올바른 답/개선 의견(선택)"
            className="flex-1 bg-ink border border-edge rounded px-2 py-1 text-xs text-slate-300 placeholder-slate-600"
          />
          <button
            onClick={onSubmitDown}
            disabled={busy}
            className="flex items-center gap-1 px-2 py-1 rounded bg-brand/20 text-brand border border-brand/40 text-xs disabled:opacity-40"
          >
            <Send size={12} /> 전송
          </button>
        </div>
      )}
    </div>
  )
}
