import { useEffect, useState } from 'react'
import { Search, Plus, Trash2, Sparkles, ArrowRightLeft, FileCode, Edit3 } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import {
  getSeoMetas, createSeoMeta, updateSeoMeta, deleteSeoMeta,
  getRedirects, createRedirect, deleteRedirect, getRobots, seoAiSuggest,
} from '../api/client'

const emptyMeta = { pathKey: '', title: '', description: '', keywords: '', ogTitle: '', ogImage: '', canonical: '', locale: 'ko' }
const emptyRedirect = { fromPath: '', toPath: '', statusCode: 301, active: true }

export default function Seo() {
  const [tab, setTab] = useState<'meta' | 'redirect'>('meta')
  const [metas, setMetas] = useState<any[]>([])
  const [redirects, setRedirects] = useState<any[]>([])
  const [metaForm, setMetaForm] = useState<any>(null)
  const [rdForm, setRdForm] = useState<any>(null)
  const [robots, setRobots] = useState('')
  const [ai, setAi] = useState<{ title: string; body: string; result: any } | null>(null)
  const writable = canWrite()

  const load = () => {
    getSeoMetas().then(d => setMetas(d || [])).catch(() => setMetas([]))
    getRedirects().then(d => setRedirects(d || [])).catch(() => setRedirects([]))
  }
  useEffect(() => { load() }, [])

  const saveMeta = async () => { if (metaForm.id) await updateSeoMeta(metaForm.id, metaForm); else await createSeoMeta(metaForm); setMetaForm(null); load() }
  const delMeta = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteSeoMeta(id); load() }
  const saveRd = async () => { await createRedirect(rdForm); setRdForm(null); load() }
  const delRd = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteRedirect(id); load() }
  const showRobots = async () => { const r = await getRobots('https://example.com'); setRobots(r?.robots || '') }
  const runAi = async () => {
    if (!ai) return
    const r = await seoAiSuggest(ai.title, ai.body)
    setAi({ ...ai, result: r })
  }

  return (
    <div>
      <PageHeader title="SEO" subtitle="메타데이터 · OG · 리다이렉트 · robots/sitemap · AI 제안"
        actions={
          <div className="flex gap-2">
            <Btn variant="ghost" onClick={showRobots}><FileCode size={15} /> robots.txt</Btn>
            <Btn variant="ghost" onClick={() => setAi({ title: '', body: '', result: null })}><Sparkles size={15} /> AI 제안</Btn>
          </div>
        } />

      <div className="flex gap-2 mb-4">
        <button onClick={() => setTab('meta')} className={`px-3 py-1.5 rounded-lg text-sm ${tab === 'meta' ? 'bg-brand text-ink font-semibold' : 'bg-card border border-edge text-slate-300'}`}>메타데이터</button>
        <button onClick={() => setTab('redirect')} className={`px-3 py-1.5 rounded-lg text-sm ${tab === 'redirect' ? 'bg-brand text-ink font-semibold' : 'bg-card border border-edge text-slate-300'}`}>리다이렉트</button>
        <div className="ml-auto">
          {writable && tab === 'meta' && <Btn onClick={() => setMetaForm({ ...emptyMeta })}><Plus size={16} /> 메타 추가</Btn>}
          {writable && tab === 'redirect' && <Btn onClick={() => setRdForm({ ...emptyRedirect })}><Plus size={16} /> 리다이렉트 추가</Btn>}
        </div>
      </div>

      {tab === 'meta' ? (
        <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-left">설명</th><th className="text-left">로케일</th><th className="text-right px-4">작업</th></tr>
            </thead>
            <tbody>
              {metas.map(m => (
                <tr key={m.id} className="border-t border-edge/50">
                  <td className="py-3 px-4 font-mono text-xs text-brand">{m.pathKey}</td>
                  <td>{m.title}</td>
                  <td className="text-slate-400 text-xs truncate max-w-[280px]">{m.description}</td>
                  <td className="text-slate-400">{m.locale}</td>
                  <td className="px-4"><div className="flex items-center justify-end gap-3">
                    {writable && <button onClick={() => setMetaForm({ ...m })} className="text-slate-400 hover:text-brand"><Edit3 size={14} /></button>}
                    {writable && <button onClick={() => delMeta(m.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>}
                  </div></td>
                </tr>
              ))}
              {metas.length === 0 && <Empty colSpan={5} msg="메타데이터가 없습니다." />}
            </tbody>
          </table>
        </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">From</th><th></th><th className="text-left">To</th><th className="text-left">코드</th><th className="text-left">활성</th><th className="text-right px-4">작업</th></tr>
            </thead>
            <tbody>
              {redirects.map(r => (
                <tr key={r.id} className="border-t border-edge/50">
                  <td className="py-3 px-4 font-mono text-xs">{r.fromPath}</td>
                  <td><ArrowRightLeft size={13} className="text-slate-500" /></td>
                  <td className="font-mono text-xs text-brand">{r.toPath}</td>
                  <td className="text-slate-400">{r.statusCode}</td>
                  <td>{r.active ? '활성' : '비활성'}</td>
                  <td className="px-4 text-right">{writable && <button onClick={() => delRd(r.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>}</td>
                </tr>
              ))}
              {redirects.length === 0 && <Empty colSpan={6} msg="리다이렉트가 없습니다." />}
            </tbody>
          </table>
        </div>
      )}

      {metaForm && (
        <Modal title={metaForm.id ? '메타 편집' : '메타 추가'} onClose={() => setMetaForm(null)} wide>
          <div className="grid grid-cols-2 gap-3">
            <Field label="경로 키"><input className="inp" value={metaForm.pathKey} onChange={e => setMetaForm({ ...metaForm, pathKey: e.target.value })} placeholder="/about" /></Field>
            <Field label="로케일"><input className="inp" value={metaForm.locale} onChange={e => setMetaForm({ ...metaForm, locale: e.target.value })} /></Field>
            <Field label="제목"><input className="inp" value={metaForm.title} onChange={e => setMetaForm({ ...metaForm, title: e.target.value })} /></Field>
            <Field label="canonical"><input className="inp" value={metaForm.canonical} onChange={e => setMetaForm({ ...metaForm, canonical: e.target.value })} /></Field>
            <Field label="설명"><textarea className="inp" value={metaForm.description} onChange={e => setMetaForm({ ...metaForm, description: e.target.value })} /></Field>
            <Field label="키워드"><textarea className="inp" value={metaForm.keywords} onChange={e => setMetaForm({ ...metaForm, keywords: e.target.value })} /></Field>
            <Field label="OG 제목"><input className="inp" value={metaForm.ogTitle} onChange={e => setMetaForm({ ...metaForm, ogTitle: e.target.value })} /></Field>
            <Field label="OG 이미지"><input className="inp" value={metaForm.ogImage} onChange={e => setMetaForm({ ...metaForm, ogImage: e.target.value })} /></Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setMetaForm(null)}>취소</Btn>
            <Btn onClick={saveMeta}>저장</Btn>
          </div>
        </Modal>
      )}

      {rdForm && (
        <Modal title="리다이렉트 추가" onClose={() => setRdForm(null)}>
          <div className="space-y-3">
            <Field label="From 경로"><input className="inp" value={rdForm.fromPath} onChange={e => setRdForm({ ...rdForm, fromPath: e.target.value })} /></Field>
            <Field label="To 경로"><input className="inp" value={rdForm.toPath} onChange={e => setRdForm({ ...rdForm, toPath: e.target.value })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="상태 코드">
                <select className="inp" value={rdForm.statusCode} onChange={e => setRdForm({ ...rdForm, statusCode: Number(e.target.value) })}>
                  {[301, 302, 307, 308].map(c => <option key={c}>{c}</option>)}
                </select>
              </Field>
              <Field label="활성">
                <select className="inp" value={String(rdForm.active)} onChange={e => setRdForm({ ...rdForm, active: e.target.value === 'true' })}>
                  <option value="true">활성</option><option value="false">비활성</option>
                </select>
              </Field>
            </div>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setRdForm(null)}>취소</Btn>
            <Btn onClick={saveRd}>저장</Btn>
          </div>
        </Modal>
      )}

      {robots && <Modal title="robots.txt" onClose={() => setRobots('')}><pre className="text-xs text-slate-400 bg-ink border border-edge rounded p-3 overflow-auto max-h-[50vh]">{robots}</pre></Modal>}

      {ai && (
        <Modal title="AI SEO 제안" onClose={() => setAi(null)} wide>
          <div className="space-y-3">
            <Field label="제목"><input className="inp" value={ai.title} onChange={e => setAi({ ...ai, title: e.target.value })} /></Field>
            <Field label="본문"><textarea className="inp" value={ai.body} onChange={e => setAi({ ...ai, body: e.target.value })} /></Field>
            <Btn onClick={runAi}><Sparkles size={14} /> 제안 생성</Btn>
            {ai.result && (
              <div className="bg-ink border border-edge rounded-lg p-3 text-sm space-y-2">
                <div><span className="text-slate-500 text-xs">메타 설명:</span> {ai.result.metaDescription}</div>
                <div><span className="text-slate-500 text-xs">키워드:</span> {(ai.result.keywords || []).join(', ')}</div>
                <div><span className="text-slate-500 text-xs">점수:</span> <span className="text-accent">{ai.result.score}</span></div>
              </div>
            )}
          </div>
        </Modal>
      )}
    </div>
  )
}
