import { useEffect, useState } from 'react'
import { Sparkles, FileText, Search, Languages, ShieldAlert, MessageSquare, Wand2 } from 'lucide-react'
import { Card, Btn, Field } from '../components/ui'
import StatusBadge from '../components/StatusBadge'
import {
  getAiStatus, aiDraft, aiSeo, aiTranslate, aiModerate, aiReviewSummary, aiSearchKeywords,
} from '../api/client'

export default function AiTools() {
  const [ollama, setOllama] = useState<boolean | null>(null)
  useEffect(() => { getAiStatus().then(d => setOllama(!!d?.ollamaAvailable)).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">콘텐츠 초안 · SEO · 번역 · 모더레이션 · 리뷰 요약 · 자연어 검색 (Ollama 온프레미스)</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">
        <DraftTool /><SeoTool /><TranslateTool /><SearchTool /><ModerateTool /><ReviewTool />
      </div>
    </div>
  )
}

function DraftTool() {
  const [kind, setKind] = useState('post'); const [topic, setTopic] = useState(''); const [tone, setTone] = useState('professional')
  const [out, setOut] = useState(''); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { const r = await aiDraft(kind, topic, tone); setOut(r?.draft || '') } finally { setBusy(false) } }
  return (
    <Card title="콘텐츠 초안 생성" icon={<FileText size={15} />}>
      <div className="grid grid-cols-2 gap-3 mb-2">
        <Field label="종류"><select className="inp" value={kind} onChange={e => setKind(e.target.value)}>{['post', 'page', 'product', 'banner'].map(k => <option key={k}>{k}</option>)}</select></Field>
        <Field label="톤"><select className="inp" value={tone} onChange={e => setTone(e.target.value)}>{['professional', 'casual', 'marketing', 'formal'].map(t => <option key={t}>{t}</option>)}</select></Field>
      </div>
      <Field label="주제"><input className="inp" value={topic} onChange={e => setTopic(e.target.value)} placeholder="예: 봄 시즌 프로모션" /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '생성 중…' : '초안 생성'}</Btn>
      {out && <pre className="mt-3 text-xs text-slate-300 bg-ink border border-edge rounded p-3 whitespace-pre-wrap max-h-48 overflow-auto">{out}</pre>}
    </Card>
  )
}

function SeoTool() {
  const [title, setTitle] = useState(''); const [body, setBody] = useState(''); const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { setOut(await aiSeo(title, body)) } finally { setBusy(false) } }
  return (
    <Card title="SEO 최적화 제안" icon={<Search size={15} />}>
      <Field label="제목"><input className="inp" value={title} onChange={e => setTitle(e.target.value)} /></Field>
      <Field label="본문"><textarea className="inp" value={body} onChange={e => setBody(e.target.value)} /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '분석 중…' : '제안 생성'}</Btn>
      {out && (
        <div className="mt-3 text-sm bg-ink border border-edge rounded p-3 space-y-1.5">
          <div><span className="text-slate-500 text-xs">메타:</span> {out.metaDescription}</div>
          <div><span className="text-slate-500 text-xs">키워드:</span> {(out.keywords || []).join(', ')}</div>
          <div><span className="text-slate-500 text-xs">점수:</span> <span className="text-accent">{out.score}</span></div>
        </div>
      )}
    </Card>
  )
}

function TranslateTool() {
  const [text, setText] = useState(''); const [target, setTarget] = useState('en'); const [out, setOut] = useState(''); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { const r = await aiTranslate(text, target); setOut(r?.translated || '') } finally { setBusy(false) } }
  return (
    <Card title="다국어 번역" icon={<Languages size={15} />}>
      <Field label="원문"><textarea className="inp" value={text} onChange={e => setText(e.target.value)} /></Field>
      <Field label="대상 로케일"><input className="inp" value={target} onChange={e => setTarget(e.target.value)} /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '번역 중…' : '번역'}</Btn>
      {out && <div className="mt-3 text-sm text-slate-200 bg-ink border border-edge rounded p-3 whitespace-pre-wrap">{out}</div>}
    </Card>
  )
}

function SearchTool() {
  const [query, setQuery] = useState(''); const [out, setOut] = useState<string[]>([]); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { const r = await aiSearchKeywords(query); setOut(r?.keywords || []) } finally { setBusy(false) } }
  return (
    <Card title="자연어 콘텐츠 검색" icon={<Wand2 size={15} />}>
      <Field label="자연어 질의"><input className="inp" value={query} onChange={e => setQuery(e.target.value)} placeholder="예: 환불 정책 관련 페이지" onKeyDown={e => e.key === 'Enter' && run()} /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '추출 중…' : '키워드 추출'}</Btn>
      {out.length > 0 && <div className="mt-3 flex flex-wrap gap-1.5">{out.map((k, i) => <span key={i} className="px-2 py-0.5 rounded bg-brand/15 text-brand text-xs border border-brand/30">{k}</span>)}</div>}
    </Card>
  )
}

function ModerateTool() {
  const [text, setText] = useState(''); const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => { setBusy(true); try { setOut(await aiModerate(text)) } finally { setBusy(false) } }
  return (
    <Card title="UGC 모더레이션 판정" icon={<ShieldAlert size={15} />}>
      <Field label="검사 텍스트"><textarea className="inp" value={text} onChange={e => setText(e.target.value)} /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '판정 중…' : '위험도 판정'}</Btn>
      {out && (
        <div className="mt-3 text-sm bg-ink border border-edge rounded p-3 flex items-center gap-3">
          <StatusBadge status={out.decision === 'APPROVE' ? 'APPROVED' : out.decision === 'REJECT' ? 'REJECTED' : 'PENDING'} />
          <span className="text-slate-400 text-xs">위험 {Math.round((out.risk ?? 0) * 100)}%</span>
          <span className="text-slate-400 text-xs">{out.reason}</span>
        </div>
      )}
    </Card>
  )
}

function ReviewTool() {
  const [text, setText] = useState(''); const [out, setOut] = useState<any>(null); const [busy, setBusy] = useState(false)
  const run = async () => {
    setBusy(true)
    try { setOut(await aiReviewSummary(text.split('\n').map(s => s.trim()).filter(Boolean))) } finally { setBusy(false) }
  }
  return (
    <Card title="리뷰 요약·감성 분석" icon={<MessageSquare size={15} />}>
      <Field label="리뷰 (줄바꿈 구분)"><textarea className="inp" value={text} onChange={e => setText(e.target.value)} placeholder={'리뷰 1\n리뷰 2'} /></Field>
      <Btn onClick={run} disabled={busy} size="sm"><Sparkles size={13} /> {busy ? '요약 중…' : '요약 생성'}</Btn>
      {out && (
        <div className="mt-3 text-sm bg-ink border border-edge rounded p-3 space-y-2">
          <div className="flex items-center gap-2"><StatusBadge status={out.sentiment} /><span className="text-slate-400 text-xs">점수 {out.score}</span></div>
          <p className="text-slate-200">{out.summary}</p>
        </div>
      )}
    </Card>
  )
}
