import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
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 { t } = useTranslation()
  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, Revenue: s.sales, Orders: s.orderCount }))
  const trendRows = (trend || []).map((t: any) => ({ name: (t.date || '').slice(5), Revenue: t.sales, Orders: t.orderCount }))
  const topRows = (top || []).map((p: any) => ({ name: p.name, 'Units Sold': p.salesCount }))

  return (
    <div>
      <h1 className="text-xl font-bold mb-5">{t('admin.dashboard.title')}</h1>
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <Kpi icon={DollarSign} label={t('admin.dashboard.todaysRevenue')} value={money(today.totalSales)} />
        <Kpi icon={ShoppingBag} label={t('admin.dashboard.todaysOrders')} value={`${today.orderCount || 0}`} />
        <Kpi icon={TrendingUp} label={t('admin.dashboard.stores')} value={`${(dash?.storeRanking || []).length}`} sub={t('admin.dashboard.storesSub')} />
        <Kpi icon={Star} label={t('admin.dashboard.largeOrders')} value={`${(dash?.bigOrders || []).length}`} sub={t('admin.dashboard.largeOrdersSub')} />
      </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">{t('admin.dashboard.revenueByStore')}</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">{t('admin.dashboard.revenueTrend')}</h2>
          <Chart type="AREA" rows={trendRows} dataKeys={['Revenue']} />
        </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">{t('admin.dashboard.bestSellers')}</h2>
          <Chart type="BAR" rows={topRows} dataKeys={['Units Sold']} />
        </div>
        <div className="bg-card border border-edge rounded-xl p-5">
          <h2 className="text-sm font-semibold mb-3">{t('admin.dashboard.storeRanking')}</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">{t('admin.dashboard.store')}</th><th className="text-right">{t('admin.dashboard.revenue')}</th><th className="text-right">{t('admin.dashboard.orders')}</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">{t('common.noData')}</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
