import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { FileText, Plus, Trash2, Edit3, Search } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getContents, deleteContent } from '../api/client'

const CONTENT_TYPES = ['', 'PAGE', 'POST', 'PRODUCT', 'LANDING']
const STATUSES = ['', 'DRAFT', 'REVIEW', 'APPROVED', 'PUBLISHED', 'ARCHIVED', 'SCHEDULED']

export default function Contents() {
  const nav = useNavigate()
  const [list, setList] = useState<any[]>([])
  const [contentType, setContentType] = useState('')
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [loading, setLoading] = useState(false)
  const writable = canWrite()

  const load = () => {
    setLoading(true)
    getContents({ contentType, status, keyword })
      .then(d => setList(d || []))
      .catch(() => setList([]))
      .finally(() => setLoading(false))
  }
  useEffect(() => { load() }, [contentType, status])

  const remove = async (id: number) => {
    if (!window.confirm('이 콘텐츠를 삭제하시겠습니까?')) return
    await deleteContent(id); load()
  }

  return (
    <div>
      <PageHeader title="콘텐츠" subtitle="페이지 · 포스트 · 헤드리스 블록 콘텐츠"
        actions={writable && <Btn onClick={() => nav('/contents/new')}><Plus size={16} /> 새 콘텐츠</Btn>} />

      <div className="flex flex-wrap items-center gap-2 mb-4">
        <div className="relative">
          <Search size={14} className="absolute left-2.5 top-2.5 text-slate-500" />
          <input value={keyword} onChange={e => setKeyword(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()}
            placeholder="제목/슬러그 검색" className="inp pl-8 w-56" />
        </div>
        <select className="inp w-36" value={contentType} onChange={e => setContentType(e.target.value)}>
          {CONTENT_TYPES.map(t => <option key={t} value={t}>{t || '전체 유형'}</option>)}
        </select>
        <select className="inp w-36" value={status} onChange={e => setStatus(e.target.value)}>
          {STATUSES.map(t => <option key={t} value={t}>{t || '전체 상태'}</option>)}
        </select>
        <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">유형</th>
              <th className="text-left">로케일</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>
            {list.map(c => (
              <tr key={c.id} className="border-t border-edge/50 hover:bg-panel/40 cursor-pointer" onClick={() => nav(`/contents/${c.id}`)}>
                <td className="py-3 px-4 font-medium flex items-center gap-2">
                  <FileText size={15} className="text-brand" />
                  <div>
                    <div>{c.title}</div>
                    <div className="text-[11px] text-slate-500 font-mono">/{c.slug}</div>
                  </div>
                </td>
                <td className="text-slate-400">{c.contentType}</td>
                <td className="text-slate-400">{c.locale}</td>
                <td><StatusBadge status={c.scheduledAt && c.status !== 'PUBLISHED' ? 'SCHEDULED' : c.status} /></td>
                <td className="text-slate-500">v{c.version}</td>
                <td className="text-slate-500 text-xs">{c.updatedAt ? new Date(c.updatedAt).toLocaleString('ko-KR') : '-'}</td>
                <td className="px-4" onClick={e => e.stopPropagation()}>
                  <div className="flex items-center justify-end gap-3">
                    <button onClick={() => nav(`/contents/${c.id}`)} className="text-slate-400 hover:text-brand"><Edit3 size={15} /></button>
                    {writable && <button onClick={() => remove(c.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={15} /></button>}
                  </div>
                </td>
              </tr>
            ))}
            {list.length === 0 && <Empty colSpan={7} msg={loading ? '불러오는 중…' : '콘텐츠가 없습니다.'} />}
          </tbody>
        </table>
      </div>
    </div>
  )
}
