import { useQuery } from '@tanstack/react-query'
import { DollarSign, ShoppingBag, TrendingUp, Star } from 'lucide-react'
import { getAnalyticsDashboard, getStoreSales, getSalesTrend, getTopProducts } from '../api/client'
import Chart from '../components/Chart'
import { money } from '../store/shop'

function Kpi({ icon: Icon, label, value, sub }: { icon: any; label: string; value: string; sub?: string }) {
  return (
    <div className="bg-card border border-edge rounded-xl p-5">
      <div className="flex items-center justify-between mb-2"><span className="text-xs text-slate-400">{label}</span><Icon size={18} className="text-brand" /></div>
      <div className="text-2xl font-bold">{value}</div>
      {sub && <div className="text-xs text-slate-500 mt-1">{sub}</div>}
    </div>
  )
}

export default function Dashboard() {
  const { data: dash } = useQuery({ queryKey: ['adash'], queryFn: () => getAnalyticsDashboard(1, 500) })
  const { data: storeSales } = useQuery({ queryKey: ['store-sales'], queryFn: () => getStoreSales(7) })
  const { data: trend } = useQuery({ queryKey: ['trend'], queryFn: () => getSalesTrend(14) })
  const { data: top } = useQuery({ queryKey: ['top'], queryFn: () => getTopProducts(8) })

  const today = dash?.today || {}
  const storeRows = (storeSales || []).map((s: any) => ({ name: s.storeCode || s.storeName, 매출: s.sales, 주문: s.orderCount }))
  const trendRows = (trend || []).map((t: any) => ({ name: (t.date || '').slice(5), 매출: t.sales, 주문: t.orderCount }))
  const topRows = (top || []).map((p: any) => ({ name: p.name, 판매량: p.salesCount }))

  return (
    <div>
      <h1 className="text-xl font-bold mb-5">대시보드</h1>
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <Kpi icon={DollarSign} label="오늘 매출" value={money(today.totalSales)} />
        <Kpi icon={ShoppingBag} label="오늘 주문" value={`${today.orderCount || 0}건`} />
        <Kpi icon={TrendingUp} label="매장 수" value={`${(dash?.storeRanking || []).length}개`} sub="활성 매장 매출 랭킹" />
        <Kpi icon={Star} label="대형 주문" value={`${(dash?.bigOrders || []).length}건`} sub="$500+ 고가 주문" />
      </div>

      <div className="grid lg:grid-cols-2 gap-5 mb-6">
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">매장별 매출 (최근 7일)</h2>
          <Chart type="BAR" rows={storeRows} dataKeys={['매출', '주문']} />
        </div>
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">매출 추이 (14일)</h2>
          <Chart type="AREA" rows={trendRows} dataKeys={['매출']} />
        </div>
      </div>

      <div className="grid lg:grid-cols-2 gap-5">
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">베스트셀러</h2>
          <Chart type="BAR" rows={topRows} dataKeys={['판매량']} />
        </div>
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">매장 매출 랭킹</h2>
          <table className="w-full text-sm">
            <thead><tr className="text-slate-400 text-xs border-b border-edge"><th className="text-left py-2">매장</th><th className="text-right">매출</th><th className="text-right">주문</th></tr></thead>
            <tbody>
              {(dash?.storeRanking || []).map((s: any, i: number) => (
                <tr key={i} className="border-b border-edge/50"><td className="py-2">{s.storeName || s.storeCode}</td><td className="text-right">{money(s.sales)}</td><td className="text-right text-slate-400">{s.orderCount}</td></tr>
              ))}
              {!(dash?.storeRanking || []).length && <tr><td colSpan={3} className="text-center text-slate-500 py-6">데이터 없음</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
