import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import { analyzeAlarm, classifyPos } from '../api/client'
import { Brain, Zap, AlertTriangle, Tag } from 'lucide-react'

export default function AiAnalysis() {
  const [alarmText, setAlarmText]     = useState('')
  const [alarmResult, setAlarmResult] = useState<string>('')
  const [posText, setPosText]         = useState('')
  const [posResult, setPosResult]     = useState<string>('')

  const alarmMut = useMutation({
    mutationFn: analyzeAlarm,
    onSuccess:  (data: any) => setAlarmResult(data.analysis || JSON.stringify(data)),
    onError:    ()          => setAlarmResult('Ollama 응답 실패 — 서비스를 확인해주세요.'),
  })

  const posMut = useMutation({
    mutationFn: classifyPos,
    onSuccess:  (data: any) => setPosResult(data.category || JSON.stringify(data)),
    onError:    ()          => setPosResult('Ollama 응답 실패 — 서비스를 확인해주세요.'),
  })

  return (
    <div className="space-y-6">
      <h1 className="text-xl font-semibold text-white flex items-center gap-2">
        <Brain size={20} className="text-brand" /> AI 분석
      </h1>

      {/* Alarm Analysis */}
      <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">
          <AlertTriangle size={16} className="text-yellow-400" /> 알람 원인 분석
        </h2>
        <textarea
          value={alarmText}
          onChange={e => setAlarmText(e.target.value)}
          rows={4}
          placeholder="알람 메시지를 입력하세요&#10;예: ESL-001 배터리 부족 경고 — Store: LG이노텍 구미, Device: ESL-A123"
          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={() => alarmMut.mutate({ message: alarmText })}
          disabled={!alarmText.trim() || alarmMut.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"
        >
          <Zap size={14} />
          {alarmMut.isPending ? '분석 중...' : 'Ollama 분석'}
        </button>
        {alarmResult && (
          <div className="mt-4 bg-panel border border-edge rounded p-4 text-sm text-gray-300 whitespace-pre-wrap">
            {alarmResult}
          </div>
        )}
      </div>

      {/* POS Classification */}
      <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">
          <Tag size={16} className="text-accent" /> POS 데이터 자동 분류
        </h2>
        <textarea
          value={posText}
          onChange={e => setPosText(e.target.value)}
          rows={4}
          placeholder="POS 데이터를 입력하세요&#10;예: 상품코드=P001, 상품명=과자, 가격=1500, 판매수량=100, 점포=이마트 광명점"
          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={() => posMut.mutate({ data: posText })}
          disabled={!posText.trim() || posMut.isPending}
          className="flex items-center gap-2 px-4 py-2 bg-accent/20 text-accent border border-accent/40 rounded hover:bg-accent/30 disabled:opacity-40 text-sm"
        >
          <Zap size={14} />
          {posMut.isPending ? '분류 중...' : 'Ollama 분류'}
        </button>
        {posResult && (
          <div className="mt-4 bg-panel border border-edge rounded p-4 text-sm text-gray-300 whitespace-pre-wrap">
            {posResult}
          </div>
        )}
      </div>
    </div>
  )
}
