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, Revenue: s.sales, Orders: s.orderCount }))
  const trendRows = (trend || []).map((t: any) => ({ name: (t.date || '').slice(5), Revenue: t.sales }))
  const topRows = (top || []).map((p: any) => ({ name: p.name, Sold: p.salesCount }))
  const tierRows = (byTier || []).map((t: any) => ({ name: t.tier, Revenue: t.sales, Customers: 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">Revenue Analytics (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}>Last {d} days</option>)}
        </select>
      </div>

      <div className="bg-card border border-edge rounded-xl p-5 mb-5">
        <div className="text-xs text-slate-400">Total Revenue (Period)</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">Revenue Trend</h2><Chart type="AREA" rows={trendRows} dataKeys={['Revenue']} /></div>
        <div className="bg-card border border-edge rounded-xl p-5"><h2 className="text-sm font-semibold mb-3">Revenue by Store</h2><Chart type="BAR" rows={storeRows} dataKeys={['Revenue', 'Orders']} /></div>
        <div className="bg-card border border-edge rounded-xl p-5"><h2 className="text-sm font-semibold mb-3">Revenue by Tier (BI)</h2><Chart type="BAR" rows={tierRows} dataKeys={['Revenue', 'Customers']} /></div>
        <div className="bg-card border border-edge rounded-xl p-5"><h2 className="text-sm font-semibold mb-3">Best Sellers Top 10</h2><Chart type="BAR" rows={topRows} dataKeys={['Sold']} /></div>
      </div>
    </div>
  )
}
