import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BarChart3 } from 'lucide-react'
import { getStoreSales, getSalesTrend, getTopProducts, getLoyaltyByTier } from '../api/client'
import Chart from '../components/Chart'
import { money } from '../store/shop'

export default function Analytics() {
  const [days, setDays] = useState(14)
  const { data: storeSales } = useQuery({ queryKey: ['an-store', days], queryFn: () => getStoreSales(days) })
  const { data: trend } = useQuery({ queryKey: ['an-trend', days], queryFn: () => getSalesTrend(days) })
  const { data: top } = useQuery({ queryKey: ['an-top'], queryFn: () => getTopProducts(10) })
  const { data: byTier } = useQuery({ queryKey: ['an-tier'], queryFn: () => getLoyaltyByTier(days) })

  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 }))
  const topRows = (top || []).map((p: any) => ({ name: p.name, 판매: p.salesCount }))
  const tierRows = (byTier || []).map((t: any) => ({ name: t.tier, 매출: t.sales, 고객: t.customers }))
  const totalSales = (storeSales || []).reduce((s: number, x: any) => s + (x.sales || 0), 0)

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><BarChart3 className="text-brand" size={22} /><h1 className="text-xl font-bold">매출 분석 (BI)</h1></div>
        <select value={days} onChange={e => setDays(Number(e.target.value))} className="bg-card border border-edge rounded-lg px-3 py-2 text-sm">
          {[7, 14, 30, 90].map(d => <option key={d} value={d}>최근 {d}일</option>)}
        </select>
      </div>

      <div className="bg-card border border-edge rounded-xl p-5 mb-5">
        <div className="text-xs text-slate-400">기간 총매출</div>
        <div className="text-3xl font-bold">{money(totalSales)}</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="AREA" rows={trendRows} dataKeys={['매출']} /></div>
        <div className="bg-card border border-edge rounded-xl p-5"><h2 className="text-sm font-semibold mb-3">매장별 매출</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">등급별 매출 (BI)</h2><Chart type="BAR" rows={tierRows} dataKeys={['매출', '고객']} /></div>
        <div className="bg-card border border-edge rounded-xl p-5"><h2 className="text-sm font-semibold mb-3">베스트셀러 Top 10</h2><Chart type="BAR" rows={topRows} dataKeys={['판매']} /></div>
      </div>
    </div>
  )
}
