import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Users, RefreshCw } from 'lucide-react'
import { getLoyaltyByTier, recalcAllLoyalty } from '../api/client'
import Chart from '../components/Chart'
import StatusBadge from '../components/StatusBadge'
import { money } from '../store/shop'

export default function Members() {
  const qc = useQueryClient()
  const { data: byTier } = useQuery({ queryKey: ['by-tier'], queryFn: () => getLoyaltyByTier(30) })

  const recalc = async () => { await recalcAllLoyalty().catch(() => {}); qc.invalidateQueries({ queryKey: ['by-tier'] }) }
  const rows = (byTier || []).map((t: any) => ({ name: t.tier, customers: t.customers, sales: t.sales }))

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><Users className="text-brand" size={22} /><h1 className="text-xl font-bold">Members (CRM)</h1></div>
        <button onClick={recalc} className="flex items-center gap-1.5 bg-card border border-edge text-sm px-3 py-2 rounded-lg text-slate-300 hover:text-brand"><RefreshCw size={14} /> Recalculate All Tiers</button>
      </div>

      <div className="grid lg:grid-cols-2 gap-5 mb-5">
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">Customer Distribution by Tier (30 days)</h2>
          <Chart type="BAR" rows={rows} dataKeys={['customers']} />
        </div>
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">Sales Contribution by Tier</h2>
          <Chart type="PIE" rows={(byTier || []).map((t: any) => ({ name: t.tier, value: t.sales }))} dataKeys={['value']} />
        </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">Tier</th><th className="text-right">Customers</th><th className="text-right">Orders</th><th className="text-right">Sales</th>
          </tr></thead>
          <tbody>
            {(byTier || []).map((t: any) => (
              <tr key={t.tier} className="border-b border-edge/50">
                <td className="p-3"><StatusBadge status={t.tier} /></td>
                <td className="text-right">{t.customers}</td>
                <td className="text-right text-slate-400">{t.orderCount}</td>
                <td className="text-right">{money(t.sales)}</td>
              </tr>
            ))}
            {!(byTier || []).length && <tr><td colSpan={4} className="text-center text-slate-500 py-8">No data</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
