import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Repeat, Pause, Play, Ban } from 'lucide-react'
import { getAdminSubscriptions, setAdminSubscriptionStatus } from '../api/client'
import StatusBadge from '../components/StatusBadge'
import { money } from '../store/shop'

export default function Subscriptions() {
  const qc = useQueryClient()
  const { data: subs } = useQuery({ queryKey: ['admin-subs'], queryFn: getAdminSubscriptions })
  const list = subs || []

  const refresh = () => qc.invalidateQueries({ queryKey: ['admin-subs'] })
  const change = async (id: number, status: string) => { await setAdminSubscriptionStatus(id, status).catch(() => {}); refresh() }
  const cancel = async (id: number) => { if (window.confirm('Cancel this subscription? It cannot be resumed.')) await change(id, 'CANCELLED') }

  return (
    <div>
      <div className="flex items-center gap-2 mb-5"><Repeat className="text-brand" size={22} /><h1 className="text-xl font-bold">Subscriptions</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">Customer</th><th className="text-left">Product</th><th className="text-left">Frequency</th><th className="text-left">Next Delivery</th><th className="text-right">Amount</th><th className="text-center">Status</th><th className="text-center">Actions</th>
          </tr></thead>
          <tbody>
            {list.map((s: any) => (
              <tr key={s.id} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3">{s.owner}</td>
                <td className="text-slate-400">{s.productName || `#${s.productId}`}</td>
                <td className="text-slate-400">{s.frequency}</td>
                <td className="text-slate-400">{s.nextDeliveryDate || '-'}</td>
                <td className="text-right">{money(s.price)}</td>
                <td className="text-center"><StatusBadge status={s.status} /></td>
                <td className="text-center">
                  <div className="inline-flex gap-1">
                    {s.status === 'ACTIVE' && (
                      <button onClick={() => change(s.id, 'PAUSED')} className="text-xs bg-amber-500/15 text-amber-400 px-2 py-1 rounded inline-flex items-center gap-1"><Pause size={12} /> Pause</button>
                    )}
                    {s.status === 'PAUSED' && (
                      <button onClick={() => change(s.id, 'ACTIVE')} className="text-xs bg-emerald-500/15 text-emerald-400 px-2 py-1 rounded inline-flex items-center gap-1"><Play size={12} /> Resume</button>
                    )}
                    {s.status !== 'CANCELLED' && (
                      <button onClick={() => cancel(s.id)} className="text-xs bg-rose-500/15 text-rose-400 px-2 py-1 rounded inline-flex items-center gap-1"><Ban size={12} /> Cancel</button>
                    )}
                    {s.status === 'CANCELLED' && <span className="text-xs text-slate-500">—</span>}
                  </div>
                </td>
              </tr>
            ))}
            {!list.length && <tr><td colSpan={7} className="text-center text-slate-500 py-8">No subscriptions found.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
