import { useEffect, useState } from 'react'
import { Megaphone, Plus, Trash2, Edit3 } from 'lucide-react'
import StatusBadge from '../components/StatusBadge'
import { PageHeader, Btn, Field, Modal, Empty, jsonStr, safeJson } from '../components/ui'
import { canWrite } from '../components/rbac'
import { getBanners, createBanner, updateBanner, deleteBanner } from '../api/client'

const BANNER_TYPES = ['HERO', 'PROMOTION', 'POPUP', 'CAMPAIGN', 'EXHIBITION']
const emptyForm = {
  name: '', bannerType: 'HERO', imageUrl: '', linkUrl: '', position: 'main_top',
  targetRule: '', sortOrder: 0, active: true, startAt: '', endAt: '',
}

export default function Banners() {
  const [list, setList] = useState<any[]>([])
  const [bannerType, setBannerType] = useState('')
  const [position, setPosition] = useState('')
  const [form, setForm] = useState<any>(null)
  const writable = canWrite()

  const load = () => getBanners({ bannerType, position }).then(d => setList(d || [])).catch(() => setList([]))
  useEffect(() => { load() }, [bannerType])

  const openNew = () => setForm({ ...emptyForm })
  const openEdit = (b: any) => setForm({ ...b, targetRule: jsonStr(b.targetRule), startAt: fmt(b.startAt), endAt: fmt(b.endAt) })
  const save = async () => {
    const payload = { ...form, targetRule: form.targetRule ? safeJson(form.targetRule, {}) : null }
    if (form.id) await updateBanner(form.id, payload); else await createBanner(payload)
    setForm(null); load()
  }
  const remove = async (id: number) => { if (!window.confirm('삭제하시겠습니까?')) return; await deleteBanner(id); load() }

  return (
    <div>
      <PageHeader title="배너 / 프로모션" subtitle="히어로 · 프로모션 · 팝업 · 기획전 · 노출 스케줄"
        actions={writable && <Btn onClick={openNew}><Plus size={16} /> 배너 추가</Btn>} />

      <div className="flex flex-wrap items-center gap-2 mb-4">
        <select className="inp w-40" value={bannerType} onChange={e => setBannerType(e.target.value)}>
          <option value="">전체 유형</option>{BANNER_TYPES.map(t => <option key={t}>{t}</option>)}
        </select>
        <input className="inp w-40" placeholder="position" value={position} onChange={e => setPosition(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()} />
        <Btn variant="ghost" onClick={load}>검색</Btn>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {list.map(b => (
          <div key={b.id} className="bg-card border border-edge rounded-xl overflow-hidden">
            <div className="aspect-[16/6] bg-ink flex items-center justify-center overflow-hidden">
              {b.imageUrl ? <img src={b.imageUrl} alt={b.name} className="object-cover w-full h-full" onError={e => { (e.target as HTMLImageElement).style.display = 'none' }} /> : <Megaphone size={26} className="text-slate-600" />}
            </div>
            <div className="p-3">
              <div className="flex items-center justify-between">
                <span className="font-medium text-sm">{b.name}</span>
                <StatusBadge status={b.active ? 'ACTIVE' : 'INACTIVE'} />
              </div>
              <div className="text-[11px] text-slate-500 mt-1">{b.bannerType} · {b.position} · 순서 {b.sortOrder}</div>
              {writable && (
                <div className="flex items-center gap-3 mt-2">
                  <button onClick={() => openEdit(b)} className="text-slate-400 hover:text-brand"><Edit3 size={14} /></button>
                  <button onClick={() => remove(b.id)} className="text-rose-400 hover:text-rose-300"><Trash2 size={14} /></button>
                </div>
              )}
            </div>
          </div>
        ))}
        {list.length === 0 && <div className="col-span-3"><Empty msg="배너가 없습니다." /></div>}
      </div>

      {form && (
        <Modal title={form.id ? '배너 편집' : '배너 추가'} onClose={() => setForm(null)}>
          <div className="space-y-3">
            <Field label="이름"><input className="inp" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="유형">
                <select className="inp" value={form.bannerType} onChange={e => setForm({ ...form, bannerType: e.target.value })}>
                  {BANNER_TYPES.map(t => <option key={t}>{t}</option>)}
                </select>
              </Field>
              <Field label="position"><input className="inp" value={form.position} onChange={e => setForm({ ...form, position: e.target.value })} /></Field>
            </div>
            <Field label="이미지 URL"><input className="inp" value={form.imageUrl} onChange={e => setForm({ ...form, imageUrl: e.target.value })} /></Field>
            <Field label="링크 URL"><input className="inp" value={form.linkUrl} onChange={e => setForm({ ...form, linkUrl: e.target.value })} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="시작"><input className="inp" type="datetime-local" value={form.startAt} onChange={e => setForm({ ...form, startAt: e.target.value })} /></Field>
              <Field label="종료"><input className="inp" type="datetime-local" value={form.endAt} onChange={e => setForm({ ...form, endAt: e.target.value })} /></Field>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <Field label="정렬 순서"><input className="inp" type="number" value={form.sortOrder} onChange={e => setForm({ ...form, sortOrder: Number(e.target.value) })} /></Field>
              <Field label="활성">
                <select className="inp" value={String(form.active)} onChange={e => setForm({ ...form, active: e.target.value === 'true' })}>
                  <option value="true">활성</option><option value="false">비활성</option>
                </select>
              </Field>
            </div>
            <Field label="타겟 규칙 (JSON)" hint='예: {"segment":"VIP"}'><textarea className="inp" value={form.targetRule} onChange={e => setForm({ ...form, targetRule: 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>
      )}
    </div>
  )
}

function fmt(v: string | null) {
  if (!v) return ''
  try { const d = new Date(v); return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 16) } catch { return '' }
}
