import { useEffect, useState } from 'react'
import { Image as ImageIcon, Plus, Trash2, Sparkles, Tag, FolderOpen, Film } from 'lucide-react'
import { PageHeader, Btn, Field, Modal, Empty } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getMedia, createMedia, autoTagMedia, updateMediaMeta, deleteMedia } from '../api/client'

const MEDIA_TYPES = ['', 'IMAGE', 'VIDEO', 'FILE']
const emptyForm = { fileName: '', mediaType: 'IMAGE', url: '', folder: '', mimeType: 'image/png', sizeBytes: 0, altText: '', tags: '' }

export default function Media() {
  const [list, setList] = useState<any[]>([])
  const [folder, setFolder] = useState('')
  const [mediaType, setMediaType] = useState('')
  const [keyword, setKeyword] = useState('')
  const [form, setForm] = useState<any>(null)
  const [edit, setEdit] = useState<any>(null)
  const [busy, setBusy] = useState<number | null>(null)
  const writable = canWrite()

  const load = () => getMedia({ folder, mediaType, keyword }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [mediaType])

  const save = async () => { await createMedia(form); setForm(null); load() }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteMedia(id); load() }
  const autoTag = async (id: number) => {
    setBusy(id)
    try { await autoTagMedia(id); load() } finally { setBusy(null) }
  }
  const saveMeta = async () => { await updateMediaMeta(edit.id, { altText: edit.altText, tags: edit.tags }); setEdit(null); load() }

  return (
    <div>
      <PageHeader title="미디어 라이브러리" subtitle="이미지 · 동영상 · 파일 · AI 대체텍스트"
        actions={writable && <Btn onClick={() => setForm({ ...emptyForm })}><Plus size={16} /> 미디어 등록</Btn>} />

      <div className="flex flex-wrap items-center gap-2 mb-4">
        <div className="relative">
          <FolderOpen size={14} className="absolute left-2.5 top-2.5 text-slate-500" />
          <input value={folder} onChange={e => setFolder(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} placeholder="폴더" className="inp pl-8 w-40" />
        </div>
        <select className="inp w-32" value={mediaType} onChange={e => setMediaType(e.target.value)}>
          {MEDIA_TYPES.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-44" />
        <Btn variant="ghost" onClick={load}>검색</Btn>
      </div>

      {list.length === 0 ? <Empty msg="미디어가 없습니다." /> : (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
          {list.map(m => (
            <div key={m.id} className="bg-card border border-edge rounded-xl overflow-hidden">
              <div className="aspect-video bg-ink flex items-center justify-center overflow-hidden">
                {m.mediaType === 'IMAGE' && m.url
                  ? <img src={m.url} alt={m.altText || m.fileName} className="object-cover w-full h-full" onError={e => { (e.target as HTMLImageElement).style.display = 'none' }} />
                  : m.mediaType === 'VIDEO' ? <Film size={28} className="text-slate-600" /> : <ImageIcon size={28} className="text-slate-600" />}
              </div>
              <div className="p-3">
                <div className="text-xs font-medium truncate" title={m.fileName}>{m.fileName}</div>
                <div className="text-[11px] text-slate-500 truncate">{m.altText || '대체텍스트 없음'}</div>
                {m.tags && <div className="text-[10px] text-brand truncate mt-1"># {m.tags}</div>}
                {writable && (
                  <div className="flex items-center gap-2 mt-2">
                    <button onClick={() => autoTag(m.id)} disabled={busy === m.id} title="AI 대체텍스트" className="text-accent hover:text-accent/80"><Sparkles size={14} /></button>
                    <button onClick={() => setEdit({ id: m.id, altText: m.altText || '', tags: m.tags || '' })} title="메타 편집" className="text-slate-400 hover:text-brand"><Tag size={14} /></button>
                    <button onClick={() => remove(m.id)} className="text-rose-400 hover:text-rose-300 ml-auto"><Trash2 size={14} /></button>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {form && (
        <Modal title="미디어 등록" onClose={() => setForm(null)}>
          <div className="space-y-3">
            <Field label="파일명"><input className="inp" value={form.fileName} onChange={e => setForm({ ...form, fileName: e.target.value })} /></Field>
            <Field label="URL"><input className="inp" value={form.url} onChange={e => setForm({ ...form, url: e.target.value })} placeholder="https://..." /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="유형">
                <select className="inp" value={form.mediaType} onChange={e => setForm({ ...form, mediaType: e.target.value })}>
                  {['IMAGE', 'VIDEO', 'FILE'].map(t => <option key={t}>{t}</option>)}
                </select>
              </Field>
              <Field label="폴더"><input className="inp" value={form.folder} onChange={e => setForm({ ...form, folder: e.target.value })} /></Field>
            </div>
            <Field label="대체 텍스트"><input className="inp" value={form.altText} onChange={e => setForm({ ...form, altText: e.target.value })} /></Field>
            <Field label="태그"><input className="inp" value={form.tags} onChange={e => setForm({ ...form, tags: 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>
      )}

      {edit && (
        <Modal title="메타 편집" onClose={() => setEdit(null)}>
          <div className="space-y-3">
            <Field label="대체 텍스트"><input className="inp" value={edit.altText} onChange={e => setEdit({ ...edit, altText: e.target.value })} /></Field>
            <Field label="태그"><input className="inp" value={edit.tags} onChange={e => setEdit({ ...edit, tags: e.target.value })} /></Field>
          </div>
          <div className="flex justify-end gap-2 mt-5">
            <Btn variant="ghost" onClick={() => setEdit(null)}>취소</Btn>
            <Btn onClick={saveMeta}>저장</Btn>
          </div>
        </Modal>
      )}
    </div>
  )
}
