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, 고객수: t.customers, 매출: 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">회원 (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} /> 전체 등급 재계산</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">등급별 고객 분포 (30일)</h2>
          <Chart type="BAR" rows={rows} dataKeys={['고객수']} />
        </div>
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">등급별 매출 기여</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">등급</th><th className="text-right">고객 수</th><th className="text-right">주문 수</th><th className="text-right">매출</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">데이터 없음</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
