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

export default function Stores() {
  const qc = useQueryClient()
  const { data: stores } = useQuery({ queryKey: ['admin-stores'], queryFn: () => getStores(false) })

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

  return (
    <div>
      <div className="flex items-center gap-2 mb-5"><StoreIcon className="text-brand" size={22} /><h1 className="text-xl font-bold">Stores</h1></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>
          </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>
              </tr>
            ))}
            {!(stores || []).length && <tr><td colSpan={8} className="text-center text-slate-500 py-8">No stores found.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
