import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Store as StoreIcon, Power, Plus, Pencil, X } from 'lucide-react'
import { getStores, setStoreActive, createStore, updateStore } from '../api/client'

const EMPTY = {
  id: 0, code: '', name: '', city: '', state: '', zip: '', address: '', phone: '',
  timezone: 'America/New_York', openTime: '09:00', closeTime: '18:00', sameDayCutoff: '12:00',
  deliveryRadiusMi: '15', dailyCapacity: '50',
}

export default function Stores() {
  const qc = useQueryClient()
  const { data: stores } = useQuery({ queryKey: ['admin-stores'], queryFn: () => getStores(false) })
  const [open, setOpen] = useState(false)
  const [form, setForm] = useState<any>({ ...EMPTY })
  const [err, setErr] = useState('')
  const [saving, setSaving] = useState(false)

  const refresh = () => qc.invalidateQueries({ queryKey: ['admin-stores'] })
  const toggle = async (id: number, active: boolean) => { await setStoreActive(id, !active).catch(() => {}); refresh() }

  const openNew = () => { setForm({ ...EMPTY }); setErr(''); setOpen(true) }
  const openEdit = (s: any) => {
    setErr('')
    setForm({
      id: s.id, code: s.code ?? '', name: s.name ?? '', city: s.city ?? '', state: s.state ?? '', zip: s.zip ?? '',
      address: s.address ?? '', phone: s.phone ?? '', timezone: s.timezone ?? 'America/New_York',
      openTime: s.openTime ?? '09:00', closeTime: s.closeTime ?? '18:00', sameDayCutoff: s.sameDayCutoff ?? '12:00',
      deliveryRadiusMi: String(s.deliveryRadiusMi ?? 15), dailyCapacity: String(s.dailyCapacity ?? 50),
    })
    setOpen(true)
  }

  const save = async () => {
    if (!form.name.trim()) { setErr('Store name is required.'); return }
    if (!form.id && !form.code.trim()) { setErr('Store code is required.'); return }
    setSaving(true); setErr('')
    const payload: any = {
      code: form.code.trim(), name: form.name.trim(), city: form.city.trim() || null, state: form.state.trim() || null,
      zip: form.zip.trim() || null, address: form.address.trim() || null, phone: form.phone.trim() || null,
      timezone: form.timezone.trim() || null, openTime: form.openTime || null, closeTime: form.closeTime || null,
      sameDayCutoff: form.sameDayCutoff || null,
      deliveryRadiusMi: form.deliveryRadiusMi === '' ? null : Number(form.deliveryRadiusMi),
      dailyCapacity: form.dailyCapacity === '' ? null : Number(form.dailyCapacity),
    }
    try {
      if (form.id) await updateStore(form.id, payload)
      else await createStore(payload)
      setOpen(false); refresh()
    } catch {
      setErr('Failed to save the store. Please check the inputs.')
    } finally { setSaving(false) }
  }

  const fld = 'bg-panel border border-edge rounded-lg px-3 py-2 text-sm'

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><StoreIcon className="text-brand" size={22} /><h1 className="text-xl font-bold">Stores</h1></div>
        <button onClick={openNew} 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 Store</button>
      </div>

      {open && (
        <div className="fixed inset-0 z-50 bg-black/60 flex items-start justify-center overflow-y-auto p-4" onClick={() => !saving && setOpen(false)}>
          <div className="bg-card border border-edge rounded-xl p-5 w-full max-w-xl mt-8 space-y-3" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-bold">{form.id ? 'Edit Store' : 'New Store'}</h2>
              <button onClick={() => setOpen(false)} className="text-slate-400 hover:text-slate-200"><X size={18} /></button>
            </div>
            {err && <div className="text-xs text-rose-400 bg-rose-500/10 border border-rose-500/30 rounded-lg px-3 py-2">{err}</div>}
            <div className="grid grid-cols-3 gap-3">
              <input value={form.code} onChange={e => setForm({ ...form, code: e.target.value })} disabled={!!form.id} placeholder="Code *" className={`${fld} ${form.id ? 'opacity-60' : ''}`} />
              <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Store Name *" className={`${fld} col-span-2`} />
            </div>
            <div className="grid grid-cols-3 gap-3">
              <input value={form.city} onChange={e => setForm({ ...form, city: e.target.value })} placeholder="City" className={fld} />
              <input value={form.state} onChange={e => setForm({ ...form, state: e.target.value })} placeholder="State" className={fld} />
              <input value={form.zip} onChange={e => setForm({ ...form, zip: e.target.value })} placeholder="ZIP" className={fld} />
            </div>
            <div className="grid grid-cols-3 gap-3">
              <input value={form.address} onChange={e => setForm({ ...form, address: e.target.value })} placeholder="Address" className={`${fld} col-span-2`} />
              <input value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} placeholder="Phone" className={fld} />
            </div>
            <div className="grid grid-cols-4 gap-3">
              <input value={form.openTime} onChange={e => setForm({ ...form, openTime: e.target.value })} placeholder="Open (09:00)" className={fld} />
              <input value={form.closeTime} onChange={e => setForm({ ...form, closeTime: e.target.value })} placeholder="Close (18:00)" className={fld} />
              <input value={form.sameDayCutoff} onChange={e => setForm({ ...form, sameDayCutoff: e.target.value })} placeholder="Same-Day Cutoff" className={fld} />
              <input value={form.timezone} onChange={e => setForm({ ...form, timezone: e.target.value })} placeholder="Timezone" className={fld} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <input type="number" value={form.deliveryRadiusMi} onChange={e => setForm({ ...form, deliveryRadiusMi: e.target.value })} placeholder="Delivery Radius (mi)" className={fld} />
              <input type="number" value={form.dailyCapacity} onChange={e => setForm({ ...form, dailyCapacity: e.target.value })} placeholder="Daily Capacity" className={fld} />
            </div>
            <div className="flex items-center justify-end gap-2 pt-1">
              <button onClick={() => setOpen(false)} disabled={saving} className="border border-edge text-slate-400 text-sm px-4 py-2 rounded-lg">Cancel</button>
              <button onClick={save} disabled={saving} className="bg-brand text-ink font-semibold text-sm px-5 py-2 rounded-lg disabled:opacity-50">{saving ? 'Saving…' : (form.id ? 'Update' : 'Create')}</button>
            </div>
          </div>
        </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">Store</th><th className="text-left">Location</th>
            <th className="text-left">Hours</th><th className="text-right">Same-Day Cutoff</th><th className="text-right">Radius (mi)</th><th className="text-right">Daily Capacity</th><th className="text-center">Status</th><th className="text-center">Manage</th>
          </tr></thead>
          <tbody>
            {(stores || []).map((s: any) => (
              <tr key={s.id} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3 font-mono text-xs text-brand">{s.code}</td>
                <td>{s.name}</td>
                <td className="text-slate-400">{s.city}, {s.state} {s.zip}</td>
                <td className="text-slate-400">{s.openTime}–{s.closeTime}</td>
                <td className="text-right text-slate-400">{s.sameDayCutoff}</td>
                <td className="text-right text-slate-400">{s.deliveryRadiusMi}</td>
                <td className="text-right text-slate-400">{s.dailyCapacity}</td>
                <td className="text-center">
                  <button onClick={() => toggle(s.id, s.active)} className={`inline-flex items-center gap-1 px-2 py-1 rounded text-xs ${s.active ? 'bg-emerald-500/15 text-emerald-400' : 'bg-slate-600/20 text-slate-400'}`}>
                    <Power size={12} /> {s.active ? 'Active' : 'Inactive'}
                  </button>
                </td>
                <td className="text-center">
                  <button onClick={() => openEdit(s)} title="Edit" className="text-xs bg-panel border border-edge text-slate-300 px-2 py-1 rounded inline-flex items-center gap-1"><Pencil size={12} /></button>
                </td>
              </tr>
            ))}
            {!(stores || []).length && <tr><td colSpan={9} className="text-center text-slate-500 py-8">No stores found.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
