import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { ragToggles, ragUpdateToggle } from '../api/client'
import { Sparkles, Server, Layers, Sliders } from 'lucide-react'

const TENANTS = ['LGINNOTEK', 'LGIT', 'EMART', 'ZIOINFO']

// 토글 메타: key, 라벨, 타입, 무거운 기법 여부(경고 배지), 옵션
const BOOL_TOGGLES: { key: string; label: string; desc: string; heavy?: boolean }[] = [
  { key: 'rag.enabled',    label: 'RAG 경유 사용', desc: '끄면 기존 Ollama/룰 경로로 동작' },
  { key: 'rag.rerank',     label: '리랭킹 (rerank)', desc: '검색 결과 재정렬 — 품질↑·비용↑', heavy: true },
  { key: 'rag.graphrag',   label: 'GraphRAG (의존성 추적)', desc: '허브→단말 연쇄 원인 추적 — 무거움', heavy: true },
  { key: 'rag.tool_use',   label: '에이전틱 tool-use (/agent)', desc: '다단계 진단 루프 — 무거움', heavy: true },
  { key: 'rag.structured', label: '구조화 출력 (/structured)', desc: '결정론 JSON — POS 분류 권장 on' },
  { key: 'rag.stream',     label: '토큰 스트리밍 (SSE)', desc: '긴 답변 점진 표시 — 동시 스트림 제한', heavy: true },
]

export default function AiTechniqueSettings() {
  const qc = useQueryClient()
  const [tenant, setTenant] = useState(TENANTS[3]) // ZIOINFO 기본
  const [draft, setDraft] = useState<Record<string, string>>({})

  const { data: t, isLoading } = useQuery({
    queryKey: ['rag-toggles', tenant],
    queryFn: () => ragToggles(tenant),
  })

  const save = useMutation({
    mutationFn: ({ key, value }: { key: string; value: string | number | boolean }) =>
      ragUpdateToggle(key, value, tenant),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['rag-toggles', tenant] }),
  })

  if (isLoading) return <div className="text-gray-400 p-8">로딩 중...</div>

  const tg: any = t || {}

  return (
    <div className="space-y-6">
      <h1 className="text-xl font-semibold text-white flex items-center gap-2">
        <Sparkles size={20} className="text-brand" /> AI 기법 설정 (중앙 guardia-rag)
      </h1>
      <p className="text-xs text-gray-500">
        테넌트별로 격리되어 저장됩니다. 무거운 기법(리랭킹·GraphRAG·tool-use·스트리밍)은 서버 RAM 보호를 위해 기본 OFF입니다.
        변경은 MANAGER 이상 권한이 필요합니다.
      </p>

      {/* 테넌트 선택 + 중앙 RAG 상태 */}
      <div className="bg-card border border-edge rounded-lg p-5 flex flex-wrap items-center gap-4">
        <div className="flex items-center gap-2">
          <Server size={16} className="text-accent" />
          <span className="text-sm text-gray-300">테넌트</span>
          <select
            value={tenant}
            onChange={e => { setTenant(e.target.value); setDraft({}) }}
            className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-100">
            {TENANTS.map(tc => <option key={tc} value={tc}>{tc}</option>)}
          </select>
        </div>
        <div className="flex items-center gap-2 text-sm">
          <span className="text-gray-400">중앙 RAG:</span>
          {tg.ragAvailable
            ? <span className="px-2 py-0.5 rounded bg-green-500/20 text-green-300 text-xs">가용</span>
            : <span className="px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 text-xs">미가용 (degraded 폴백)</span>}
        </div>
      </div>

      {/* 불리언 토글들 */}
      <div className="bg-card border border-edge rounded-lg p-5 space-y-3">
        <h2 className="text-sm font-medium text-white flex items-center gap-2 mb-2">
          <Layers size={16} className="text-brand" /> 기법 On/Off
        </h2>
        {BOOL_TOGGLES.map(b => {
          const on = !!tg[camel(b.key)]
          return (
            <div key={b.key} className="flex items-center justify-between border-b border-edge/60 pb-3">
              <div>
                <div className="text-sm text-gray-200 flex items-center gap-2">
                  {b.label}
                  {b.heavy && <span className="px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-300 text-[10px]">무거움</span>}
                </div>
                <div className="text-xs text-gray-500">{b.desc}</div>
              </div>
              <button
                onClick={() => save.mutate({ key: b.key, value: !on })}
                disabled={save.isPending}
                className={`relative w-11 h-6 rounded-full transition ${on ? 'bg-brand' : 'bg-edge'}`}>
                <span className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white transition ${on ? 'translate-x-5' : ''}`} />
              </button>
            </div>
          )
        })}
      </div>

      {/* 파라미터 (mode / top_k / step / model) */}
      <div className="bg-card border border-edge rounded-lg p-5 space-y-4">
        <h2 className="text-sm font-medium text-white flex items-center gap-2 mb-2">
          <Sliders size={16} className="text-accent" /> 파라미터
        </h2>

        <Param label="검색 모드 (retrieval_mode)" hint="vector | hybrid | graph (GraphRAG on 이면 graph 강제)">
          <select
            value={draft['rag.retrieval_mode'] ?? tg.retrievalMode ?? 'vector'}
            onChange={e => setDraft(d => ({ ...d, 'rag.retrieval_mode': e.target.value }))}
            className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-100">
            <option value="vector">vector</option>
            <option value="hybrid">hybrid (BM25+벡터)</option>
            <option value="graph">graph (GraphRAG)</option>
          </select>
        </Param>

        <NumParam label="top_k (검색 문서 수)" k="rag.top_k" cur={tg.topK} min={1} max={20} draft={draft} setDraft={setDraft} />
        <NumParam label="에이전트 최대 스텝 (agent_max_steps)" k="rag.agent_max_steps" cur={tg.agentMaxSteps} min={1} max={8} draft={draft} setDraft={setDraft} />
        <FloatParam label="temperature" k="rag.temperature" cur={tg.temperature} draft={draft} setDraft={setDraft} />
        <FloatParam label="신뢰도 임계 (faithfulness_threshold)" k="rag.faithfulness_threshold" cur={tg.faithfulnessThreshold} draft={draft} setDraft={setDraft} />

        <Param label="생성 모델 (generation_model)" hint="소형 모델 권장 (예: llama3.2:1b)">
          <input
            value={draft['rag.generation_model'] ?? tg.generationModel ?? ''}
            onChange={e => setDraft(d => ({ ...d, 'rag.generation_model': e.target.value }))}
            className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-100 w-48" />
        </Param>

        <div className="pt-2 flex flex-wrap gap-2">
          {Object.keys(draft).map(k => (
            <button key={k}
              onClick={() => save.mutate({ key: k, value: draft[k] })}
              disabled={save.isPending}
              className="text-xs px-3 py-1.5 rounded bg-brand/80 text-white hover:bg-brand">
              저장: {k.replace('rag.', '')}
            </button>
          ))}
          {Object.keys(draft).length > 0 && (
            <button onClick={() => setDraft({})}
              className="text-xs px-3 py-1.5 rounded bg-edge/60 text-gray-300 hover:bg-edge">변경 취소</button>
          )}
        </div>
      </div>
    </div>
  )
}

function camel(key: string) {
  const m: Record<string, string> = {
    'rag.enabled': 'ragEnabled', 'rag.rerank': 'rerank', 'rag.graphrag': 'graphrag',
    'rag.tool_use': 'toolUse', 'rag.structured': 'structured', 'rag.stream': 'stream',
  }
  return m[key] || key
}

function Param({ label, hint, children }: { label: string; hint?: string; children: any }) {
  return (
    <div className="flex items-center justify-between">
      <div>
        <div className="text-sm text-gray-200">{label}</div>
        {hint && <div className="text-xs text-gray-500">{hint}</div>}
      </div>
      {children}
    </div>
  )
}

function NumParam({ label, k, cur, min, max, draft, setDraft }: any) {
  return (
    <Param label={label} hint={`범위 ${min}~${max}`}>
      <input type="number" min={min} max={max}
        value={draft[k] ?? cur ?? min}
        onChange={e => setDraft((d: any) => ({ ...d, [k]: e.target.value }))}
        className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-100 w-24" />
    </Param>
  )
}

function FloatParam({ label, k, cur, draft, setDraft }: any) {
  return (
    <Param label={label} hint="0.0 ~ 1.0">
      <input type="number" step="0.1" min={0} max={1}
        value={draft[k] ?? cur ?? 0}
        onChange={e => setDraft((d: any) => ({ ...d, [k]: e.target.value }))}
        className="bg-panel border border-edge rounded px-3 py-1.5 text-sm text-gray-100 w-24" />
    </Param>
  )
}
