import { useEffect, useState } from 'react'
import { Languages, Plus, Trash2, Sparkles, Wand2 } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getLocales, getResources, createResource, deleteResource, translateText, translateBatch } from '../api/client'

export default function I18n() {
  const [locales, setLocales] = useState<string[]>([])
  const [locale, setLocale] = useState('')
  const [resources, setResources] = useState<any[]>([])
  const [form, setForm] = useState<any>(null)
  const [transBox, setTransBox] = useState<{ text: string; target: string; result: string } | null>(null)
  const [batch, setBatch] = useState<{ source: string; target: string } | null>(null)
  const [msg, setMsg] = useState('')
  const writable = canWrite()

  useEffect(() => {
    getLocales().then((d: string[]) => { setLocales(d || []); if (d?.[0]) setLocale(d[0]) }).catch(() => setLocales([]))
  }, [])
  const load = () => getResources(locale).then(d => setResources(d || [])).catch(() => setResources([]))
  useEffect(() => { if (locale) load() }, [locale])

  const save = async () => { await createResource({ locale: form.locale, resourceKey: form.resourceKey, value: form.value }); setForm(null); load() }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteResource(id); load() }

  const doTranslate = async () => {
    if (!transBox) return
    const r = await translateText(transBox.text, transBox.target)
    setTransBox({ ...transBox, result: r?.translated || '' })
  }
  const doBatch = async () => {
    if (!batch) return
    const r = await translateBatch(batch.source, batch.target)
    setMsg(`일괄 번역 완료: ${r?.translated ?? 0}건 → ${r?.targetLocale || batch.target}`)
    setBatch(null); load()
  }

  return (
    <div>
      <PageHeader title="다국어 (i18n)" subtitle="로케일 · 번역 리소스 · AI 번역"
        actions={
          <div className="flex gap-2">
            <Btn variant="ghost" onClick={() => setTransBox({ text: '', target: 'en', result: '' })}><Sparkles size={15} /> AI 번역</Btn>
            <Btn variant="ghost" onClick={() => setBatch({ source: 'ko', target: 'en' })}><Wand2 size={15} /> 일괄 번역</Btn>
            {writable && <Btn onClick={() => setForm({ locale: locale || 'ko', resourceKey: '', value: '' })}><Plus size={16} /> 리소스 추가</Btn>}
          </div>
        } />

      {msg && <div className="mb-4 text-sm rounded-lg px-4 py-2.5 bg-brand/10 border border-brand/30 text-brand">{msg}</div>}

      <div className="flex items-center gap-2 mb-4">
        <Languages size={16} className="text-slate-400" />
        <select className="inp w-40" value={locale} onChange={e => setLocale(e.target.value)}>
          {locales.length === 0 && <option value="">로케일 없음</option>}
          {locales.map(l => <option key={l} value={l}>{l}</option>)}
        </select>
      </div>

      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="text-slate-500 text-xs bg-panel">
            <tr><th className="text-left py-3 px-4">키</th><th className="text-left">값</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {resources.map(r => (
              <tr key={r.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-mono text-xs text-brand">{r.resourceKey}</td>
                <td className="text-slate-300">{r.value}</td>
                <td className="px-4 text-right">{writable && <button onClick={() => remove(r.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={15} /></button>}</td>
              </tr>
            ))}
            {resources.length === 0 && <Empty colSpan={3} msg="번역 리소스가 없습니다." />}
          </tbody>
        </table>
      </div>

      {form && (
        <Modal title="리소스 추가" onClose={() => setForm(null)}>
          <div className="space-y-3">
            <Field label="로케일"><input className="inp" value={form.locale} onChange={e => setForm({ ...form, locale: e.target.value })} /></Field>
            <Field label="키"><input className="inp" value={form.resourceKey} onChange={e => setForm({ ...form, resourceKey: e.target.value })} placeholder="home.title" /></Field>
            <Field label="값"><textarea className="inp" value={form.value} onChange={e => setForm({ ...form, value: e.target.value })} /></Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setForm(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}

      {transBox && (
        <Modal title="AI 번역" onClose={() => setTransBox(null)}>
          <div className="space-y-3">
            <Field label="원문"><textarea className="inp" value={transBox.text} onChange={e => setTransBox({ ...transBox, text: e.target.value })} /></Field>
            <Field label="대상 로케일"><input className="inp" value={transBox.target} onChange={e => setTransBox({ ...transBox, target: e.target.value })} /></Field>
            <Btn onClick={doTranslate}><Sparkles size={14} /> 번역</Btn>
            {transBox.result && <Field label="번역 결과"><div className="inp min-h-[60px] whitespace-pre-wrap">{transBox.result}</div></Field>}
          </div>
        </Modal>
      )}

      {batch && (
        <Modal title="일괄 번역" onClose={() => setBatch(null)}>
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <Field label="원본 로케일"><input className="inp" value={batch.source} onChange={e => setBatch({ ...batch, source: e.target.value })} /></Field>
              <Field label="대상 로케일"><input className="inp" value={batch.target} onChange={e => setBatch({ ...batch, target: e.target.value })} /></Field>
            </div>
            <p className="text-[11px] text-slate-500">원본 로케일의 모든 리소스를 대상 로케일로 AI 번역하여 생성합니다.</p>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setBatch(null)}>취소</Btn>
            <Btn onClick={doBatch}><Wand2 size={14} /> 일괄 번역 실행</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
