import { useEffect, useState } from 'react'
import {
  Sparkles, AlertTriangle, TrendingUp, Wrench, LineChart, Search, Boxes, CalendarClock,
} from 'lucide-react'
import { Card, Btn, Field } from '../components/ui'
import {
  getAiStatus, aiDefectRootCause, aiForecast, aiPredictiveMaintenance,
  aiSpcAnomaly, aiParseQuery, aiSafetyStock, aiScheduleOptimize,
} from '../api/client'

function Output({ data }: { data: any }) {
  if (data == null) return null
  if (typeof data === 'string') return <pre className="mt-3 text-xs text-slate-300 bg-ink border border-edge rounded p-3 whitespace-pre-wrap max-h-56 overflow-auto">{data}</pre>
  return <pre className="mt-3 text-xs text-slate-300 bg-ink border border-edge rounded p-3 whitespace-pre-wrap max-h-56 overflow-auto">{JSON.stringify(data, null, 2)}</pre>
}

export default function AiTools() {
  const [ollama, setOllama] = useState<boolean | null>(null)
  useEffect(() => { getAiStatus().then(d => setOllama(!!(d?.ollamaAvailable ?? d?.available))).catch(() => setOllama(false)) }, [])

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold flex items-center gap-2"><Sparkles className="text-accent" size={20} /> AI 도구</h1>
          <p className="text-sm text-slate-400 mt-0.5">불량분석 · 생산예측 · 예지보전 · SPC이상 · 자연어조회 · 안전재고 · 일정최적화 (Ollama 온프레미스 + Java 폴백)</p>
        </div>
        <span className={`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg border ${ollama ? 'text-accent border-accent/30 bg-accent/10' : 'text-slate-400 border-edge bg-card'}`}>
          <span className={`w-1.5 h-1.5 rounded-full ${ollama ? 'bg-accent' : 'bg-slate-500'}`} />
          Ollama {ollama === null ? '확인 중' : ollama ? '온라인' : '오프라인 (Java 폴백)'}
        </span>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        <DefectTool /><ForecastTool /><MaintenanceTool /><SpcTool />
        <QueryTool /><SafetyStockTool /><ScheduleTool />
      </div>
    </div>
  )
}

function DefectTool() {
  const [code, setCode] = useState(''); const [ctx, setCtx] = useState(''); const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { setOut(await aiDefectRootCause({ defectCode: code, context: ctx })) } finally { setBusy(false) } }
  return (
    <Card title="불량 원인 분석" icon={<AlertTriangle size={15} />}>
      <Field label="불량 코드"><input className="inp" value={code} onChange={e => setCode(e.target.value)} placeholder="예: D-CRACK-01" /></Field>
      <Field label="컨텍스트(공정/설비/자재)"><textarea className="inp" value={ctx} onChange={e => setCtx(e.target.value)} /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '분석 중…' : '원인 분석'}</Btn>
      <Output data={out} />
    </Card>
  )
}

function ForecastTool() {
  const [item, setItem] = useState(''); const [days, setDays] = useState(30); const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { setOut(await aiForecast({ itemCode: item, days })) } finally { setBusy(false) } }
  return (
    <Card title="수요·생산량 예측" icon={<TrendingUp size={15} />}>
      <div className="grid grid-cols-2 gap-3">
        <Field label="품목코드"><input className="inp" value={item} onChange={e => setItem(e.target.value)} /></Field>
        <Field label="예측 기간(일)"><input type="number" className="inp" value={days} onChange={e => setDays(Number(e.target.value))} /></Field>
      </div>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '예측 중…' : '예측'}</Btn>
      <Output data={out} />
    </Card>
  )
}

function MaintenanceTool() {
  const [eq, setEq] = useState(''); const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { setOut(await aiPredictiveMaintenance({ equipmentCode: eq })) } finally { setBusy(false) } }
  return (
    <Card title="설비 예지보전" icon={<Wrench size={15} />}>
      <Field label="설비 코드"><input className="inp" value={eq} onChange={e => setEq(e.target.value)} placeholder="예: EQ-CNC-01" /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '분석 중…' : '정비 권고'}</Btn>
      <Output data={out} />
    </Card>
  )
}

function SpcTool() {
  const [code, setCode] = useState(''); const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { setOut(await aiSpcAnomaly({ chartCode: code })) } finally { setBusy(false) } }
  return (
    <Card title="SPC 이상 감지" icon={<LineChart size={15} />}>
      <Field label="관리도 코드"><input className="inp" value={code} onChange={e => setCode(e.target.value)} /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '감지 중…' : '이상 감지'}</Btn>
      <Output data={out} />
    </Card>
  )
}

function QueryTool() {
  const [q, setQ] = useState(''); const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { setOut(await aiParseQuery({ query: q })) } finally { setBusy(false) } }
  return (
    <Card title="작업지시·재고 자연어 조회" icon={<Search size={15} />}>
      <Field label="자연어 질의"><input className="inp" value={q} onChange={e => setQ(e.target.value)} placeholder="예: 지난주 지연된 작업지시" onKeyDown={e => e.key === 'Enter' && run()} /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '해석 중…' : '질의 해석'}</Btn>
      <Output data={out} />
    </Card>
  )
}

function SafetyStockTool() {
  const [item, setItem] = useState(''); const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { setOut(await aiSafetyStock({ itemCode: item })) } finally { setBusy(false) } }
  return (
    <Card title="재고 최적화·안전재고 추천" icon={<Boxes size={15} />}>
      <Field label="품목코드"><input className="inp" value={item} onChange={e => setItem(e.target.value)} /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '분석 중…' : '추천'}</Btn>
      <Output data={out} />
    </Card>
  )
}

function ScheduleTool() {
  const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { setOut(await aiScheduleOptimize({})) } finally { setBusy(false) } }
  return (
    <Card title="생산 일정 최적화" icon={<CalendarClock size={15} />}>
      <p className="text-xs text-slate-400 mb-2">현재 작업지시·설비 부하 기반으로 일정 최적화를 제안합니다.</p>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '최적화 중…' : '일정 최적화 제안'}</Btn>
      <Output data={out} />
    </Card>
  )
}
