import { useEffect, useState } from 'react'
import { Package, Plus, Trash2, Globe, Sparkles, ScanText, GripVertical } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, Card, safeJson } from '../components/ui'
import { canWrite, canPublish } from '../components/rbac'
import {
  getProducts, getProduct, createProduct, updateProduct, publishProduct,
  productAiDraft, productOcrExtract, deleteProduct,
} from '../api/client'

const STATUSES = ['', 'DRAFT', 'PUBLISHED', 'ARCHIVED']
const emptyForm = { mallProductId: '', productName: '', summary: '', detailBlocks: [] as any[], specs: '', locale: 'ko' }

export default function Products() {
  const [list, setList] = useState<any[]>([])
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [editor, setEditor] = useState<any>(null)   // 상세 빌더 모달
  const [aiBusy, setAiBusy] = useState(false)
  const [ocrId, setOcrId] = useState('')
  const writable = canWrite()
  const publishable = canPublish()

  const load = () => getProducts({ status, keyword }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [status])

  const openNew = () => setEditor({ ...emptyForm, _new: true })
  const openEdit = async (id: number) => {
    const p = await getProduct(id)
    setEditor({ ...p, detailBlocks: safeJson(p.detailBlocks, []), _new: false })
  }
  const save = async () => {
    const { _new, id, ...payload } = editor
    if (_new) await createProduct(payload); else await updateProduct(id, payload)
    setEditor(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteProduct(id); load() }
  const publish = async (id: number) => { await publishProduct(id); load() }

  const aiDraftFill = async () => {
    setAiBusy(true)
    try {
      const r = await productAiDraft(editor.productName || '상품', 'marketing')
      if (r?.draft) setEditor((e: any) => ({ ...e, detailBlocks: [...e.detailBlocks, { type: 'text', text: r.draft }] }))
    } catch { /* noop */ } finally { setAiBusy(false) }
  }
  const ocrFill = async () => {
    if (!ocrId) return
    try {
      const r = await productOcrExtract(ocrId)
      setEditor((e: any) => ({
        ...e,
        productName: e.productName || r?.productName || '',
        summary: e.summary || r?.summary || '',
        specs: e.specs || r?.specs || '',
      }))
    } catch { /* noop */ }
  }

  const addBlock = () => setEditor((e: any) => ({ ...e, detailBlocks: [...e.detailBlocks, { type: 'text', text: '' }] }))
  const setBlock = (i: number, text: string) => setEditor((e: any) => {
    const b = [...e.detailBlocks]; b[i] = { ...b[i], text }; return { ...e, detailBlocks: b }
  })
  const delBlock = (i: number) => setEditor((e: any) => ({ ...e, detailBlocks: e.detailBlocks.filter((_: any, j: number) => j !== i) }))

  return (
    <div>
      <PageHeader title="상품 콘텐츠" subtitle="상품 상세페이지 빌더 · Mall 연계 · AI 초안 · OCR 추출"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 상품 콘텐츠</Btn>} />

      <div className="flex flex-wrap items-center gap-2 mb-4">
        <select className="inp w-36" value={status} onChange={e => setStatus(e.target.value)}>
          {STATUSES.map(t => <option key={t} value={t}>{t || '전체 상태'}</option>)}
        </select>
        <input value={keyword} onChange={e => setKeyword(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} placeholder="상품명 검색" className="inp w-52" />
        <Btn variant="ghost" onClick={load}>검색</Btn>
      </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">Mall ID</th><th className="text-left">로케일</th><th className="text-left">상태</th><th className="text-right px-4">작업</th></tr>
          </thead>
          <tbody>
            {list.map(p => (
              <tr key={p.id} className="border-t border-edge/50">
                <td className="py-3 px-4 font-medium flex items-center gap-2"><Package size={15} className="text-brand" />{p.productName}</td>
                <td className="text-slate-400 font-mono text-xs">{p.mallProductId || '-'}</td>
                <td className="text-slate-400">{p.locale}</td>
                <td><StatusBadge status={p.status} /></td>
                <td className="px-4">
                  <div className="flex items-center justify-end gap-3">
                    <button onClick={() => openEdit(p.id)} className="text-slate-400 hover:text-brand text-xs">편집</button>
                    {publishable && p.status !== 'PUBLISHED' && <button onClick={() => publish(p.id)} title="발행" className="text-emerald-400 hover:text-emerald-300"><Globe size={15} /></button>}
                    {writable && <button onClick={() => remove(p.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={15} /></button>}
                  </div>
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={5} msg="상품 콘텐츠가 없습니다." />}
          </tbody>
        </table>
      </div>

      {editor && (
        <Modal title={editor._new ? '상품 콘텐츠 작성' : '상품 콘텐츠 편집'} onClose={() => setEditor(null)} wide>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-3">
              <Field label="상품명"><input className="inp" value={editor.productName} onChange={e => setEditor({ ...editor, productName: e.target.value })} /></Field>
              <div className="grid grid-cols-2 gap-3">
                <Field label="Mall 상품 ID"><input className="inp" value={editor.mallProductId || ''} onChange={e => setEditor({ ...editor, mallProductId: e.target.value })} /></Field>
                <Field label="로케일">
                  <select className="inp" value={editor.locale} onChange={e => setEditor({ ...editor, locale: e.target.value })}>
                    {['ko', 'en', 'ja', 'zh'].map(t => <option key={t}>{t}</option>)}
                  </select>
                </Field>
              </div>
              <Field label="요약"><textarea className="inp" value={editor.summary || ''} onChange={e => setEditor({ ...editor, summary: e.target.value })} /></Field>
              <Field label="사양 (specs)"><textarea className="inp" value={editor.specs || ''} onChange={e => setEditor({ ...editor, specs: e.target.value })} /></Field>
              <Field label="OCR 문서로 채우기">
                <div className="flex gap-2">
                  <input className="inp" placeholder="documentId" value={ocrId} onChange={e => setOcrId(e.target.value)} />
                  <Btn variant="ghost" onClick={ocrFill}><ScanText size={13} /> 추출</Btn>
                </div>
              </Field>
            </div>

            <Card title="상세페이지 빌더">
              <div className="flex gap-2 mb-3">
                <Btn size="sm" variant="ghost" onClick={addBlock}><Plus size={13} /> 텍스트 블록</Btn>
                <Btn size="sm" variant="ghost" disabled={aiBusy} onClick={aiDraftFill}><Sparkles size={13} /> {aiBusy ? 'AI…' : 'AI 초안'}</Btn>
              </div>
              {editor.detailBlocks.length === 0 && <div className="text-center text-slate-500 text-xs py-6 border border-dashed border-edge rounded">블록을 추가하세요.</div>}
              <div className="space-y-2 max-h-72 overflow-auto">
                {editor.detailBlocks.map((b: any, i: number) => (
                  <div key={i} className="bg-panel border border-edge rounded p-2">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[11px] text-brand flex items-center gap-1"><GripVertical size={11} className="text-slate-500" /> #{i + 1}</span>
                      <button onClick={() => delBlock(i)} className="text-rose-400 hover:text-rose-300"><Trash2 size={12} /></button>
                    </div>
                    <textarea className="inp text-xs" value={b.text || ''} onChange={e => setBlock(i, e.target.value)} />
                  </div>
                ))}
              </div>
            </Card>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setEditor(null)}>취소</Btn>
            <Btn onClick={save}>저장</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
