import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Megaphone, Sparkles, Plus, BarChart3 } from 'lucide-react'
import { getAdminEvents, createEvent, publishEvent, endEvent, deleteEvent, getEventPerformance, aiEventCopy } from '../api/client'
import StatusBadge from '../components/StatusBadge'
import { money } from '../store/shop'

const TYPES = ['DISCOUNT', 'POINT_BONUS', 'GIFT', 'TIER_ONLY', 'SEASON']

export default function Events() {
  const qc = useQueryClient()
  const [status, setStatus] = useState('')
  const [open, setOpen] = useState(false)
  const [perf, setPerf] = useState<any>(null)
  const [form, setForm] = useState<any>({ code: '', title: '', eventType: 'DISCOUNT', description: '', startDate: '', endDate: '', targetTiers: '', bonusPointRate: 0 })
  const [aiCopyMsg, setAiCopyMsg] = useState('')

  const { data: events } = useQuery({ queryKey: ['admin-events', status], queryFn: () => getAdminEvents(status, '', false) })

  const refresh = () => qc.invalidateQueries({ queryKey: ['admin-events'] })
  const create = async () => { await createEvent({ ...form, status: 'DRAFT', banners: [] }).catch(() => {}); setOpen(false); refresh() }
  const publish = async (id: number) => { await publishEvent(id).catch(() => {}); refresh() }
  const end = async (id: number) => { await endEvent(id).catch(() => {}); refresh() }
  const del = async (id: number) => { await deleteEvent(id).catch(() => {}); refresh() }
  const showPerf = async (id: number) => { const r = await getEventPerformance(id).catch(() => null); setPerf(r) }
  const genCopy = async () => {
    const r = await aiEventCopy(form.eventType, form.title || 'Spring Season', 'friendly').catch(() => null)
    if (r) { setForm({ ...form, title: r.headline || form.title, description: r.subtext || form.description }); setAiCopyMsg(`AI copy generated (${r.source})`) }
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><Megaphone className="text-brand" size={22} /><h1 className="text-xl font-bold">Events & Campaigns</h1></div>
        <div className="flex items-center gap-2">
          <select value={status} onChange={e => setStatus(e.target.value)} className="bg-card border border-edge rounded-lg px-3 py-2 text-sm">
            <option value="">All</option>{['DRAFT', 'PUBLISHED', 'ENDED'].map(s => <option key={s} value={s}>{s}</option>)}
          </select>
          <button onClick={() => setOpen(!open)} className="flex items-center gap-1.5 bg-brand text-ink text-sm font-semibold px-3 py-2 rounded-lg"><Plus size={15} /> New Event</button>
        </div>
      </div>

      {open && (
        <div className="bg-card border border-edge rounded-xl p-5 mb-5 space-y-3">
          <div className="grid grid-cols-3 gap-3">
            <input value={form.code} onChange={e => setForm({ ...form, code: e.target.value })} placeholder="Code" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
            <input value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} placeholder="Title" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm col-span-2" />
          </div>
          <textarea value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} placeholder="Description" rows={2} className="w-full bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          <div className="grid grid-cols-4 gap-3">
            <select value={form.eventType} onChange={e => setForm({ ...form, eventType: e.target.value })} className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm">{TYPES.map(t => <option key={t}>{t}</option>)}</select>
            <input type="date" value={form.startDate} onChange={e => setForm({ ...form, startDate: e.target.value })} className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
            <input type="date" value={form.endDate} onChange={e => setForm({ ...form, endDate: e.target.value })} className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
            <input value={form.targetTiers} onChange={e => setForm({ ...form, targetTiers: e.target.value })} placeholder="Target Tiers (GOLD, VIP)" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          </div>
          <div className="flex items-center gap-2">
            <button onClick={genCopy} className="flex items-center gap-1.5 bg-brand2 text-white text-sm px-3 py-2 rounded-lg"><Sparkles size={14} /> Generate AI Copy</button>
            {aiCopyMsg && <span className="text-xs text-accent">{aiCopyMsg}</span>}
            <button onClick={create} className="ml-auto bg-brand text-ink font-semibold text-sm px-5 py-2 rounded-lg">Create</button>
            <button onClick={() => setOpen(false)} className="border border-edge text-slate-400 text-sm px-4 py-2 rounded-lg">Cancel</button>
          </div>
        </div>
      )}

      {perf && (
        <div className="bg-card border border-edge rounded-xl p-4 mb-5 flex items-center gap-6 text-sm">
          <span className="flex items-center gap-1.5 text-brand"><BarChart3 size={15} /> {perf.title}</span>
          <span className="text-slate-400">Participations {perf.participations} · Participants {perf.participants}</span>
          <span className="text-slate-400">Linked Orders {perf.linkedOrders} · Attributed Sales {money(perf.attributedSales)}</span>
          <button onClick={() => setPerf(null)} className="ml-auto text-slate-500 text-xs">Close</button>
        </div>
      )}

      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead><tr className="text-slate-400 text-xs border-b border-edge bg-panel">
            <th className="text-left p-3">Code</th><th className="text-left">Title</th><th className="text-left">Type</th><th className="text-left">Period</th><th className="text-left">Target</th><th className="text-center">Status</th><th className="text-center">Actions</th>
          </tr></thead>
          <tbody>
            {(events || []).map((ev: any) => (
              <tr key={ev.id} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3 font-mono text-xs text-brand">{ev.code}</td>
                <td>{ev.title}</td>
                <td className="text-slate-400 text-xs">{ev.eventType}</td>
                <td className="text-slate-400 text-xs">{ev.startDate}~{ev.endDate}</td>
                <td className="text-slate-400 text-xs">{ev.targetTiers || 'All'}</td>
                <td className="text-center"><StatusBadge status={ev.status} /></td>
                <td className="text-center">
                  <div className="inline-flex gap-1">
                    {ev.status === 'DRAFT' && <button onClick={() => publish(ev.id)} className="text-xs bg-emerald-500/15 text-emerald-400 px-2 py-1 rounded">Publish</button>}
                    {ev.status === 'PUBLISHED' && <button onClick={() => end(ev.id)} className="text-xs bg-slate-600/20 text-slate-400 px-2 py-1 rounded">End</button>}
                    <button onClick={() => showPerf(ev.id)} className="text-xs bg-panel border border-edge text-slate-300 px-2 py-1 rounded">Performance</button>
                    <button onClick={() => del(ev.id)} className="text-xs bg-rose-500/15 text-rose-400 px-2 py-1 rounded">Delete</button>
                  </div>
                </td>
              </tr>
            ))}
            {!(events || []).length && <tr><td colSpan={7} className="text-center text-slate-500 py-8">No events found.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
