import { useEffect, useState } from 'react'
import { Cpu, Cloud, ShieldCheck, Zap, AlertTriangle, ThumbsUp, ThumbsDown, Send } from 'lucide-react'
import {
  getAiConfig, updateAiConfig, testAiConfig, sendAiFeedback,
  type AiConfigDto, type AiProvider, type ClaudeModel, type AiTestResult,
} from '../api/adminAiConfig'

// 프로바이더 카탈로그 — glm 은 RAM 경고 배지(선택 허용·콜드로드 실패 시 폴백).
const PROVIDERS: { id: AiProvider; label: string; sub: string; icon: any; ram?: boolean; ext?: boolean }[] = [
  { id: 'claude',   label: 'Claude (외부)',        sub: 'Anthropic Messages API · 소유자 승인 예외', icon: Cloud, ext: true },
  { id: 'qwen3',    label: 'Qwen3 (온프레미스)',   sub: 'qwen3:1.7b · 중국 top1 오픈소스(기본)',     icon: Cpu },
  { id: 'deepseek', label: 'DeepSeek (온프레미스)', sub: 'deepseek-r1:1.5b · 추론 특화',              icon: Cpu },
  { id: 'glm',      label: 'GLM (온프레미스)',     sub: 'glm4:9b · RAM 여유 필요',                    icon: Cpu, ram: true },
  { id: 'ollama',   label: 'Ollama 로컬',          sub: 'llama3 등 기존 소형 폴백',                   icon: Cpu },
]

const CLAUDE_MODELS: { id: ClaudeModel; label: string }[] = [
  { id: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6 (기본)' },
  { id: 'claude-haiku-4-5',  label: 'Claude Haiku 4.5' },
  { id: 'claude-opus-4-8',   label: 'Claude Opus 4.8' },
]

const Badge = ({ text, color = 'bg-blue-100 text-blue-700' }: any) => (
  <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${color}`}>{text}</span>
)

export default function AiPlatformSettings() {
  const [cfg, setCfg]         = useState<AiConfigDto | null>(null)
  const [provider, setProvider] = useState<AiProvider>('ollama')
  const [claudeModel, setClaudeModel] = useState<ClaudeModel>('claude-sonnet-4-6')
  const [busy, setBusy]       = useState(false)
  const [msg, setMsg]         = useState('')
  const [test, setTest]       = useState<AiTestResult | null>(null)

  // 피드백 위젯(학습 루프)
  const [fbFeature, setFbFeature] = useState('insights')
  const [fbAnswer, setFbAnswer]   = useState('')
  const [fbCorrection, setFbCorrection] = useState('')
  const [fbMsg, setFbMsg]         = useState('')

  const load = () => getAiConfig().then(c => {
    setCfg(c)
    setProvider(c.provider)
    setClaudeModel((CLAUDE_MODELS.find(m => m.id === c.claudeModel)?.id) ?? 'claude-sonnet-4-6')
  }).catch(() => setMsg('설정을 불러오지 못했습니다. 관리자(SUPERADMIN) 권한이 필요합니다.'))

  useEffect(() => { load() }, [])

  const save = async () => {
    setBusy(true); setMsg(''); setTest(null)
    try {
      const updated = await updateAiConfig({ provider, claudeModel: provider === 'claude' ? claudeModel : undefined })
      setCfg(updated)
      setMsg('저장되었습니다. 다음 AI 호출부터 반영됩니다.')
    } catch (e: any) {
      setMsg(e?.response?.data?.message ?? '저장 실패')
    } finally { setBusy(false) }
  }

  const runTest = async () => {
    setBusy(true); setTest(null); setMsg('')
    try { setTest(await testAiConfig()) }
    catch (e: any) { setTest({ ok: false, degraded: true, message: e?.response?.data?.message ?? '연결 테스트 실패' }) }
    finally { setBusy(false) }
  }

  const submitFeedback = async (verdict: 'up' | 'down') => {
    setFbMsg('')
    try {
      const r = await sendAiFeedback({ feature: fbFeature, answer: fbAnswer, verdict, correction: fbCorrection })
      setFbMsg(`피드백 반영됨 · 로컬 저장 ${r.storedLocal ? '성공' : '(비활성)'} · 중앙 학습 전달`)
      setFbCorrection('')
    } catch {
      setFbMsg('피드백 전송 실패')
    }
  }

  return (
    <div className="space-y-5 max-w-4xl">
      <div>
        <h1 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
          <Cloud className="text-blue-600" size={22} /> AI 플랫폼 설정
        </h1>
        <p className="text-slate-500 text-sm mt-1">
          LLM 제공자·모델을 선택합니다. <b>API 키는 서버 환경변수(ANTHROPIC_API_KEY)로만 주입</b>되어 화면·응답에 노출되지 않습니다.
          Claude 실패 시 자동으로 Ollama(온프레미스)로 폴백합니다.
        </p>
      </div>

      {msg && <div className="card text-sm text-slate-700 py-3">{msg}</div>}

      {/* 현재 상태 */}
      {cfg && (
        <div className="card flex flex-wrap gap-4 items-center">
          <div className="text-sm text-slate-600">현재 provider <Badge text={cfg.provider} /></div>
          <div className="text-sm text-slate-600">Ollama 모델 <Badge text={cfg.ollamaTextModel} color="bg-slate-100 text-slate-600" /></div>
          <div className="text-sm text-slate-600 flex items-center gap-1">
            <ShieldCheck size={14} className={cfg.claudeKeySet ? 'text-emerald-500' : 'text-slate-400'} />
            Claude 키 {cfg.claudeKeySet
              ? <Badge text="설정됨" color="bg-emerald-100 text-emerald-700" />
              : <Badge text="미설정(폴백)" color="bg-amber-100 text-amber-700" />}
          </div>
          <div className="text-sm text-slate-600">AI {cfg.aiEnabled
            ? <Badge text="활성" color="bg-emerald-100 text-emerald-700" />
            : <Badge text="비활성(규칙기반)" color="bg-amber-100 text-amber-700" />}</div>
        </div>
      )}

      {/* provider 선택 */}
      <div className="card">
        <div className="text-sm font-semibold text-slate-700 mb-3">프로바이더 선택</div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {PROVIDERS.map(p => {
            const Icon = p.icon
            const active = provider === p.id
            return (
              <button key={p.id} onClick={() => setProvider(p.id)}
                className={`text-left border rounded-lg p-3 transition-colors ${active ? 'border-blue-500 bg-blue-50' : 'border-slate-200 hover:bg-slate-50'}`}>
                <div className="flex items-center gap-2">
                  <Icon size={16} className={active ? 'text-blue-600' : 'text-slate-400'} />
                  <span className="font-medium text-sm text-slate-700">{p.label}</span>
                  {p.ext && <Badge text="외부" color="bg-blue-100 text-blue-700" />}
                  {p.ram && <Badge text="RAM 증설 필요" color="bg-amber-100 text-amber-700" />}
                </div>
                <div className="text-xs text-slate-500 mt-1">{p.sub}</div>
              </button>
            )
          })}
        </div>

        {provider === 'glm' && (
          <div className="mt-3 text-xs text-amber-600 flex items-center gap-1">
            <AlertTriangle size={14} /> glm4:9b 은 약 5.5GB 로드 — 현재 서버 RAM 여유 부족 시 콜드로드 실패하여 폴백될 수 있습니다.
          </div>
        )}

        {provider === 'claude' && (
          <div className="mt-4">
            <div className="text-sm font-semibold text-slate-700 mb-2">Claude 모델</div>
            <select value={claudeModel} onChange={e => setClaudeModel(e.target.value as ClaudeModel)}
              className="border border-slate-200 rounded-lg px-3 py-2 text-sm w-full max-w-sm">
              {CLAUDE_MODELS.map(m => <option key={m.id} value={m.id}>{m.label}</option>)}
            </select>
            {cfg && !cfg.claudeKeySet && (
              <div className="mt-2 text-xs text-amber-600 flex items-center gap-1">
                <AlertTriangle size={14} /> 서버에 ANTHROPIC_API_KEY 미설정 — 저장은 되나 실제로는 Ollama 로 폴백 동작합니다.
              </div>
            )}
          </div>
        )}

        <div className="mt-4 flex gap-2">
          <button onClick={save} disabled={busy} className="btn-primary disabled:opacity-50">저장</button>
          <button onClick={runTest} disabled={busy}
            className="btn-secondary flex items-center gap-1 disabled:opacity-50">
            <Zap size={14} /> 연결 테스트
          </button>
        </div>

        {test && (
          <div className={`mt-3 text-sm rounded-lg px-4 py-2 border ${test.ok ? 'border-emerald-200 bg-emerald-50 text-emerald-700' : 'border-amber-200 bg-amber-50 text-amber-700'}`}>
            {test.ok ? '정상' : '주의'} · {test.message}
          </div>
        )}
      </div>

      {/* AI 답변 피드백(학습 루프) */}
      <div className="card">
        <div className="text-sm font-semibold text-slate-700 mb-1 flex items-center gap-2"><ThumbsUp size={16} className="text-blue-600" /> AI 답변 피드백 (학습 루프)</div>
        <p className="text-xs text-slate-500 mb-3">
          피드백은 로컬 DuckDB(ai_feedback)에 적재되고 중앙 guardia-rag 로 전달됩니다. 입력 텍스트는 서버에서 PII 마스킹 후 저장됩니다(인사 데이터 보호).
        </p>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div>
            <label className="text-xs text-slate-500">기능</label>
            <select value={fbFeature} onChange={e => setFbFeature(e.target.value)}
              className="border border-slate-200 rounded-lg px-3 py-2 text-sm w-full mt-1">
              <option value="insights">HR 인사이트</option>
              <option value="turnover">이직 예측</option>
              <option value="performance">성과 예측</option>
              <option value="recruitment">채용 추천</option>
              <option value="orghealth">조직 건강도</option>
              <option value="resume">이력서 분석</option>
            </select>
          </div>
        </div>
        <textarea value={fbAnswer} onChange={e => setFbAnswer(e.target.value)} rows={2}
          placeholder="평가할 AI 답변(선택)" className="border border-slate-200 rounded-lg px-3 py-2 text-sm w-full mt-3" />
        <textarea value={fbCorrection} onChange={e => setFbCorrection(e.target.value)} rows={2}
          placeholder="교정/올바른 답(선택)" className="border border-slate-200 rounded-lg px-3 py-2 text-sm w-full mt-2" />
        <div className="mt-3 flex gap-2">
          <button onClick={() => submitFeedback('up')}
            className="border border-emerald-300 text-emerald-700 px-4 py-2 rounded-lg text-sm flex items-center gap-1 hover:bg-emerald-50">
            <ThumbsUp size={14} /> 좋음
          </button>
          <button onClick={() => submitFeedback('down')}
            className="border border-rose-300 text-rose-700 px-4 py-2 rounded-lg text-sm flex items-center gap-1 hover:bg-rose-50">
            <ThumbsDown size={14} /> 개선 필요
          </button>
          <button onClick={() => submitFeedback('down')}
            className="btn-secondary flex items-center gap-1">
            <Send size={14} /> 교정 제출
          </button>
        </div>
        {fbMsg && <div className="mt-2 text-xs text-slate-500">{fbMsg}</div>}
      </div>
    </div>
  )
}
