import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import { PageHeader, Button } from '../components/ui'
import { Icon } from '../lib/icons'
import { aiChat, aiAnalyzeAlarm, aiGenerateSignText, aiRecommendAd } from '../api/client'

// AI 어시스턴트 — 온프레미스/Claude(AiTextRouter) 경유. 알람 분석·간판 문구·광고 추천·챗.
type Msg = { role: 'user' | 'ai'; text: string }

export default function AiAssistant() {
  const [msgs, setMsgs] = useState<Msg[]>([])
  const [input, setInput] = useState('')

  const push = (m: Msg) => setMsgs(p => [...p, m])
  const asText = (r: any) => r?.text || r?.result || r?.analysis || r?.recommendation || r?.message || JSON.stringify(r)

  const chatMut = useMutation({
    mutationFn: (m: string) => aiChat(m),
    onSuccess: r => push({ role: 'ai', text: asText(r) }),
    onError: () => push({ role: 'ai', text: 'AI 응답을 가져오지 못했습니다. (degraded)' }),
  })
  const alarmMut = useMutation({
    mutationFn: () => aiAnalyzeAlarm({ message: input || '게이트웨이 오프라인 다수 발생', alarmType: 'DEVICE', severity: 'HIGH' }),
    onSuccess: r => push({ role: 'ai', text: '[알람 분석]\n' + asText(r) }),
  })
  const signMut = useMutation({
    mutationFn: () => aiGenerateSignText({ bizName: input || '지오분식', message: '신메뉴 출시' }),
    onSuccess: r => push({ role: 'ai', text: '[간판 문구]\n' + asText(r) }),
  })
  const adMut = useMutation({
    mutationFn: () => aiRecommendAd({ storeCode: 'STORE001', season: '여름' }),
    onSuccess: r => push({ role: 'ai', text: '[광고 추천]\n' + asText(r) }),
  })

  const send = () => {
    if (!input.trim()) return
    push({ role: 'user', text: input })
    chatMut.mutate(input)
    setInput('')
  }

  const busy = chatMut.isPending || alarmMut.isPending || signMut.isPending || adMut.isPending

  return (
    <div>
      <PageHeader title="AI 어시스턴트" subtitle="온프레미스 sLLM / Claude(AiTextRouter) 경유 · 외부 호출은 Claude 프로바이더 예외만" />

      <div className="flex gap-2 mb-4 flex-wrap">
        <Button variant="ghost" icon="alarm" onClick={() => alarmMut.mutate()} disabled={busy}>알람 원인 분석</Button>
        <Button variant="ghost" icon="editor" onClick={() => signMut.mutate()} disabled={busy}>간판 문구 생성</Button>
        <Button variant="ghost" icon="ad" onClick={() => adMut.mutate()} disabled={busy}>광고 추천</Button>
      </div>

      <div className="bg-card border border-edge rounded-lg h-[52vh] overflow-auto p-4 space-y-3">
        {msgs.length === 0 && (
          <div className="text-center text-gray-500 text-sm pt-16">
            <Icon name="ai" size={32} className="mx-auto mb-2 text-edge" />
            질문을 입력하거나 위 도구를 사용하세요.
          </div>
        )}
        {msgs.map((m, i) => (
          <div key={i} className={`flex ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
            <div className={`max-w-[75%] rounded-lg px-3 py-2 text-sm whitespace-pre-wrap ${m.role === 'user' ? 'bg-brand text-white' : 'bg-panel border border-edge text-gray-200'}`}>
              {m.text}
            </div>
          </div>
        ))}
        {busy && <div className="text-gray-500 text-sm">AI 응답 생성 중...</div>}
      </div>

      <div className="flex gap-2 mt-3">
        <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()}
          placeholder="질문 또는 도구 파라미터(상호명/알람 내용)를 입력..."
          className="flex-1 bg-ink border border-edge rounded px-3 py-2 text-sm text-white outline-none focus:border-brand" />
        <Button icon="send" onClick={send} disabled={busy}>전송</Button>
      </div>
    </div>
  )
}
