// AI 답변 피드백 UI(👍/👎 + 교정) — 재사용 컴포넌트.
//   AI 결과 화면 하단에 배치. 로컬 DuckDB + 중앙 guardia-rag 로 전달(둘 다). PII 는 서버 마스킹.
import { useState } from 'react'
import { ThumbsUp, ThumbsDown } from 'lucide-react'
import { sendAiFeedback } from '../api/aiFeedback'

interface Props {
  /** 기능 식별자(예: recommend / review-summary / cs-reply / ai-config). */
  feature: string
  /** 사용자 질의/프롬프트(선택). */
  question?: string
  /** AI 답변(선택). */
  answer?: string
  className?: string
}

/**
 * 👍/👎 피드백 위젯. 👎 선택 시 교정 입력을 노출한다.
 * 서버(/api/ai/feedback)가 로컬 DuckDB 기록 + 중앙 rag 전달을 동시에 수행한다.
 */
export default function AiFeedback({ feature, question, answer, className }: Props) {
  const [verdict, setVerdict] = useState<'up' | 'down' | null>(null)
  const [correction, setCorrection] = useState('')
  const [sent, setSent] = useState(false)
  const [busy, setBusy] = useState(false)

  const submit = async (v: 'up' | 'down', corr?: string) => {
    setBusy(true)
    try {
      await sendAiFeedback({ feature, question, answer, verdict: v, correction: corr })
      setSent(true)
    } catch {
      // 피드백 실패는 조용히 무시(본기능 무영향)
      setSent(true)
    } finally {
      setBusy(false)
    }
  }

  const pick = (v: 'up' | 'down') => {
    setVerdict(v)
    if (v === 'up') submit('up')
  }

  if (sent) {
    return <div className={`text-xs text-emerald-300 ${className ?? ''}`}>피드백 감사합니다.</div>
  }

  return (
    <div className={`flex flex-col gap-2 ${className ?? ''}`}>
      <div className="flex items-center gap-2 text-xs text-slate-400">
        <span>이 답변이 도움이 되었나요?</span>
        <button
          onClick={() => pick('up')}
          disabled={busy}
          aria-label="도움됨"
          className={`p-1.5 rounded-lg border transition-colors ${
            verdict === 'up' ? 'bg-emerald-500/15 border-emerald-500/40 text-emerald-300'
              : 'bg-ink border-edge text-slate-300 hover:border-emerald-500/50'
          }`}
        >
          <ThumbsUp size={14} />
        </button>
        <button
          onClick={() => pick('down')}
          disabled={busy}
          aria-label="도움 안됨"
          className={`p-1.5 rounded-lg border transition-colors ${
            verdict === 'down' ? 'bg-rose-500/15 border-rose-500/40 text-rose-300'
              : 'bg-ink border-edge text-slate-300 hover:border-rose-500/50'
          }`}
        >
          <ThumbsDown size={14} />
        </button>
      </div>
      {verdict === 'down' && (
        <div className="flex items-center gap-2">
          <input
            value={correction}
            onChange={e => setCorrection(e.target.value)}
            placeholder="더 나은 답변/교정 (선택)"
            className="flex-1 px-3 py-1.5 rounded-lg bg-ink border border-edge text-xs focus:border-brand outline-none"
          />
          <button
            onClick={() => submit('down', correction)}
            disabled={busy}
            className="px-3 py-1.5 rounded-lg bg-brand text-ink text-xs font-semibold disabled:opacity-40"
          >
            보내기
          </button>
        </div>
      )}
    </div>
  )
}
