import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { CalendarClock, Plus, Sparkles } from 'lucide-react'
import { getHolidays, createHoliday, getStores, aiDemandForecast } from '../api/client'

const SEASONS = ['valentine', 'mothers_day', 'christmas', 'thanksgiving']

export default function Schedule() {
  const qc = useQueryClient()
  const [form, setForm] = useState<any>({ holidayDate: '', name: '', blocked: true, surgeMultiplier: 1.0, storeId: null })
  const [season, setSeason] = useState('valentine')
  const [forecast, setForecast] = useState<any>(null)

  const { data: holidays } = useQuery({ queryKey: ['admin-holidays'], queryFn: getHolidays })
  const { data: stores } = useQuery({ queryKey: ['sch-stores'], queryFn: () => getStores(false) })

  const add = async () => { if (!form.holidayDate) return; await createHoliday(form).catch(() => {}); setForm({ ...form, holidayDate: '', name: '' }); qc.invalidateQueries({ queryKey: ['admin-holidays'] }) }
  const runForecast = async () => { const r = await aiDemandForecast(season, 14).catch(() => null); setForecast(r) }
  const storeName = (id: number) => stores?.find((s: any) => s.id === id)?.code || `#${id}`

  return (
    <div>
      <div className="flex items-center gap-2 mb-5"><CalendarClock className="text-brand" size={22} /><h1 className="text-xl font-bold">Schedule · Holidays · Surge</h1></div>

      <div className="bg-card border border-edge rounded-xl p-5 mb-5">
        <div className="text-sm font-semibold mb-3">Add Holiday / Surge</div>
        <div className="grid grid-cols-5 gap-3">
          <input type="date" value={form.holidayDate} onChange={e => setForm({ ...form, holidayDate: e.target.value })} className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Name" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          <label className="flex items-center gap-2 text-sm text-slate-300"><input type="checkbox" checked={form.blocked} onChange={e => setForm({ ...form, blocked: e.target.checked })} /> Block Delivery</label>
          <input type="number" step="0.1" value={form.surgeMultiplier} onChange={e => setForm({ ...form, surgeMultiplier: Number(e.target.value) })} placeholder="Surge Multiplier" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          <button onClick={add} className="flex items-center gap-1.5 bg-brand text-ink font-semibold rounded-lg px-3 py-2 text-sm justify-center"><Plus size={15} /> Add</button>
        </div>
      </div>

      <div className="bg-card border border-edge rounded-xl overflow-hidden mb-6">
        <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">Date</th><th className="text-left">Name</th><th className="text-center">Block Delivery</th><th className="text-right">Surge Multiplier</th><th className="text-left">Store</th>
          </tr></thead>
          <tbody>
            {(holidays || []).map((h: any) => (
              <tr key={h.id || h.holidayDate} className="border-b border-edge/50">
                <td className="p-3">{h.holidayDate}</td>
                <td className="text-slate-400">{h.name}</td>
                <td className="text-center">{h.blocked ? <span className="text-rose-400">Blocked</span> : <span className="text-slate-500">–</span>}</td>
                <td className="text-right">{h.surgeMultiplier > 1 ? <span className="text-amber-400">×{h.surgeMultiplier}</span> : '–'}</td>
                <td className="text-slate-400 text-xs">{h.storeId ? storeName(h.storeId) : 'All'}</td>
              </tr>
            ))}
            {!(holidays || []).length && <tr><td colSpan={5} className="text-center text-slate-500 py-8">No holidays registered.</td></tr>}
          </tbody>
        </table>
      </div>

      <div className="bg-card border border-edge rounded-xl p-5">
        <div className="flex items-center gap-2 mb-3">
          <Sparkles size={16} className="text-brand" /><span className="text-sm font-semibold">AI Peak-Season Demand Forecast</span>
          <select value={season} onChange={e => setSeason(e.target.value)} className="ml-auto bg-panel border border-edge rounded-lg px-3 py-1.5 text-sm">{SEASONS.map(s => <option key={s}>{s}</option>)}</select>
          <button onClick={runForecast} className="bg-brand2 text-white text-sm px-3 py-1.5 rounded-lg">Run Forecast</button>
        </div>
        {forecast && (
          <table className="w-full text-sm">
            <thead><tr className="text-slate-400 text-xs border-b border-edge"><th className="text-left py-2">Store</th><th className="text-right">Recent Orders</th><th className="text-right">Forecast Orders</th><th className="text-right">Multiplier</th></tr></thead>
            <tbody>
              {(forecast.forecast || []).map((f: any, i: number) => (
                <tr key={i} className="border-b border-edge/50"><td className="py-2">{storeName(f.storeId)}</td><td className="text-right text-slate-400">{f.recentOrders}</td><td className="text-right text-brand">{f.predictedOrders}</td><td className="text-right text-amber-400">×{f.multiplier}</td></tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  )
}
