import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import { Sparkles, Send, Quote, AlertTriangle, ShieldCheck } from 'lucide-react'
import { wiseAsk } from '../api/client'

/**
 * WISE AI — Enterprise AI for Trusted Knowledge.
 * 질문 → 중앙 guardia-rag(/rag/answer) 경유 근거 답변 → 인용 카드 + 환각차단(abstained)/degraded 배지.
 * ESN 백엔드 POST /api/wise/ask 프록시(EsnRagClient.answer 재사용) 경유. 온프레미스·테넌트 격리.
 */

type Cite = any

function citeLabel(c: Cite): string {
  if (c == null) return '문서'
  if (typeof c === 'string') return c
  const src = c.source || c.document || c.doc || c.title || c.chunk_id || c.id || '문서'
  const loc = c.page != null ? ` p.${c.page}` : (c.location ? ` ${c.location}` : '')
  const sup = c.support != null ? ` · ${Math.round(Number(c.support) * 100)}%` : ''
  return `${src}${loc}${sup}`
}

export default function WiseAiPage() {
  const [query, setQuery] = useState('')
  const [res, setRes] = useState<any>(null)
  const tenantCode = localStorage.getItem('esn_tenant') || undefined

  const askMut = useMutation({
    mutationFn: () => wiseAsk(query, undefined, tenantCode),
    onSuccess: (data: any) => setRes(data),
    onError: () => setRes({ answer: 'AI 서비스 일시 불가 — 잠시 후 다시 시도해 주세요.', degraded: true, degraded_reason: 'request_failed' }),
  })

  const run = () => { if (query.trim()) askMut.mutate() }

  const citations: Cite[] = Array.isArray(res?.citations) ? res.citations : []
  const sources: Cite[] = Array.isArray(res?.sources) ? res.sources : []
  const items = citations.length ? citations : sources
  const abstained = res?.abstained === true
  const degraded = res?.degraded === true

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-xl font-semibold text-white flex items-center gap-2">
          <Sparkles size={20} className="text-brand" /> WISE AI
        </h1>
        <p className="text-sm text-gray-400 mt-0.5">
          Enterprise AI for Trusted Knowledge · 근거·인용·환각차단 (중앙 guardia-rag 경유 · 온프레미스)
        </p>
      </div>

      <div className="bg-card border border-edge rounded-lg p-5">
        <h2 className="text-sm font-medium text-white mb-3 flex items-center gap-2">
          <ShieldCheck size={16} className="text-brand" /> 근거 기반 질의
        </h2>
        <textarea
          value={query}
          onChange={e => setQuery(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) run() }}
          rows={4}
          placeholder="ESL/HCore 운영 지식을 자연어로 질의하세요&#10;예: 허브 오프라인 시 하위 단말 알람 처리 절차는?"
          className="w-full bg-panel border border-edge rounded px-3 py-2 text-sm text-gray-300 placeholder-gray-600 resize-none mb-3"
        />
        <button
          onClick={run}
          disabled={!query.trim() || askMut.isPending}
          className="flex items-center gap-2 px-4 py-2 bg-brand/20 text-brand border border-brand/40 rounded hover:bg-brand/30 disabled:opacity-40 text-sm"
        >
          <Send size={14} />
          {askMut.isPending ? '질의 중...' : '질의 (Ctrl+Enter)'}
        </button>

        {res && (
          <div className="mt-4 bg-panel border border-edge rounded p-4">
            {/* 환각차단(abstained) / degraded 배지 */}
            {abstained && (
              <div className="mb-3 flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg bg-amber-500/10 border border-amber-500/30 text-amber-300">
                <AlertTriangle size={13} /> 근거가 부족해 답변을 보류했습니다 (오류 아님 · 안내)
              </div>
            )}
            {degraded && !abstained && (
              <div className="mb-3 inline-flex items-center gap-1.5 text-xs px-2.5 py-1 rounded-lg bg-gray-500/10 border border-edge text-gray-400">
                degraded{res?.degraded_reason ? ` · ${res.degraded_reason}` : ''}
              </div>
            )}

            {/* 답변(plain text) */}
            <div className="text-sm text-gray-200 whitespace-pre-wrap">{res?.answer || '(응답 없음)'}</div>

            {/* 인용 카드 */}
            <div className="mt-3">
              {items.length > 0 ? (
                <>
                  <div className="text-[11px] text-gray-400 mb-1.5 flex items-center gap-1"><Quote size={12} /> 근거 인용 ({items.length})</div>
                  <div className="flex flex-wrap gap-1.5">
                    {items.map((c, i) => (
                      <span key={i} className="text-[10px] px-2 py-1 rounded-md bg-card border border-edge text-gray-300">{citeLabel(c)}</span>
                    ))}
                  </div>
                </>
              ) : (
                !abstained && !degraded && <div className="text-[11px] text-gray-500">근거 문서 없음</div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
