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

/**
 * WISE AI — 중앙 guardia-rag 경유 근거·인용 기반 질의응답. [ZIOINFO-ESN]
 *  - 질문 → 답변(plain text) → 인용 카드(sources) → 근거 부족 시 보류(abstained) → 미가용 시 degraded
 *  - 온프레미스 전용(외부 API 미사용). 기존 /ai(AI 분석) 페이지는 그대로 보존 — 본 화면은 별개 레이어.
 */
export default function WiseAiPage() {
  const [query, setQuery] = useState('')
  const [res, setRes] = useState<any>(null)

  const mut = useMutation({
    mutationFn: (q: string) => wiseAsk(q),
    onSuccess: (data: any) => setRes(data || { degraded: true, degraded_reason: 'no_response' }),
    onError: () => setRes({ degraded: true, degraded_reason: 'request_failed' }),
  })

  const ask = () => {
    if (!query.trim() || mut.isPending) return
    setRes(null)
    mut.mutate(query.trim())
  }

  const sources: any[] = res?.sources || res?.citations || []
  const abstained = res?.abstained === true
  const degraded = res?.degraded === true

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <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-xs text-gray-500 mt-0.5">Enterprise AI for Trusted Knowledge</p>
        </div>
        <span className="flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-full bg-card border border-edge text-emerald-400">
          <Cpu size={13} /> 중앙 guardia-rag · 외부 API 미사용
        </span>
      </div>

      {/* 질문 입력 */}
      <div className="bg-card border border-edge rounded-lg p-5">
        <textarea
          value={query}
          onChange={e => setQuery(e.target.value)}
          rows={4}
          placeholder="질문을 입력하세요&#10;예: LG이노텍 구미 매장의 ESL 펌웨어 배포 절차를 알려줘"
          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={ask}
          disabled={!query.trim() || mut.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} />
          {mut.isPending ? '질의 중...' : '질문하기'}
        </button>
      </div>

      {/* 답변 */}
      {res && (
        <div className="bg-card border border-edge rounded-lg p-5 space-y-4">
          {/* 상태 배지 */}
          <div className="flex flex-wrap gap-1.5">
            {abstained && (
              <span className="flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-md bg-amber-500/10 border border-amber-500/40 text-amber-300">
                <ShieldAlert size={13} /> 근거가 부족해 답변을 보류했습니다
              </span>
            )}
            {degraded && (
              <span className="text-xs px-3 py-1.5 rounded-md bg-panel border border-edge text-gray-400">
                일시적으로 AI 품질이 저하됨{res?.degraded_reason ? ` (${res.degraded_reason})` : ''}
              </span>
            )}
          </div>

          {/* 답변 본문 (plain text) */}
          {!abstained && (
            <div className="bg-panel border border-edge rounded p-4 text-sm text-gray-200 whitespace-pre-wrap">
              {res?.answer || (degraded ? 'AI 서비스가 일시적으로 불가합니다. 잠시 후 다시 시도해주세요.' : '답변이 없습니다.')}
            </div>
          )}

          {/* 인용 카드 */}
          <div>
            <div className="text-xs text-gray-400 mb-1.5 flex items-center gap-1">
              <Quote size={12} /> 근거 인용
            </div>
            {sources.length > 0 ? (
              <div className="flex flex-wrap gap-2">
                {sources.map((s: any, i: number) => (
                  <span key={i} className="text-[11px] px-2 py-1 rounded-md bg-panel border border-edge text-gray-300">
                    {s.source || s.document || s.title || s.chunk_id || `근거 ${i + 1}`}
                    {s.page != null && ` · p.${s.page}`}
                    {s.support != null && ` · ${Math.round(s.support * 100)}%`}
                  </span>
                ))}
              </div>
            ) : (
              <div className="text-xs text-gray-500">근거 문서 없음</div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
