import { useQuery } from '@tanstack/react-query'
import { Package, Users, Warehouse, Store, TrendingUp, TrendingDown, Receipt, Banknote, Calendar } from 'lucide-react'
import { PageHeader } from '@/components/PageHeader'
import { SalesChart } from '@/components/SalesChart'
import { api } from '@/lib/api'
import type { PagedResult, SalesStatsResponse } from '@/lib/types'

interface MeResponse {
  sub: string
  name: string
  email: string
  roles: string[]
  orgId: string
}

function useCount(url: string) {
  return useQuery({
    queryKey: [url, 'count'],
    queryFn: async () => (await api.get<PagedResult<unknown>>(`${url}?pageSize=1`)).data.total,
  })
}

const fmt = new Intl.NumberFormat('ru', { maximumFractionDigits: 0 })
const fmtMoney = (n: number) => fmt.format(n)

interface KpiCardProps {
  icon: React.ComponentType<{ className?: string }>
  label: string
  value: string | number
  hint?: string
  delta?: { value: number; positive: boolean }
}

function KpiCard({ icon: Icon, label, value, hint, delta }: KpiCardProps) {
  return (
    <div className="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-5">
      <div className="flex items-start justify-between">
        <div className="min-w-0">
          <div className="text-xs uppercase tracking-wide text-slate-500">{label}</div>
          <div className="mt-1 text-2xl font-semibold text-slate-900 dark:text-slate-100 truncate">
            {value}
          </div>
          {hint && <div className="mt-0.5 text-xs text-slate-400">{hint}</div>}
        </div>
        <Icon className="w-5 h-5 text-slate-400 flex-shrink-0" />
      </div>
      {delta && (
        <div className={`mt-2 inline-flex items-center gap-1 text-xs font-medium ${delta.positive ? 'text-green-600' : 'text-red-600'}`}>
          {delta.positive ? <TrendingUp className="w-3 h-3" /> : <TrendingDown className="w-3 h-3" />}
          {delta.positive ? '+' : ''}{delta.value.toFixed(1)}% к прошлому месяцу
        </div>
      )}
    </div>
  )
}

function MiniCard({ icon: Icon, label, value, isLoading }: {
  icon: React.ComponentType<{ className?: string }>
  label: string
  value: number | undefined
  isLoading: boolean
}) {
  return (
    <div className="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-4">
      <div className="flex items-center justify-between">
        <span className="text-xs text-slate-500">{label}</span>
        <Icon className="w-4 h-4 text-slate-400" />
      </div>
      <div className="text-xl font-semibold mt-1.5 text-slate-900 dark:text-slate-100">
        {isLoading ? '…' : value !== undefined ? fmt.format(value) : '—'}
      </div>
    </div>
  )
}

export function DashboardPage() {
  const me = useQuery({
    queryKey: ['me'],
    queryFn: async () => (await api.get<MeResponse>('/api/me')).data,
  })
  const stats = useQuery({
    queryKey: ['/api/sales/retail/stats'],
    queryFn: async () => (await api.get<SalesStatsResponse>('/api/sales/retail/stats?days=30')).data,
  })
  const products = useCount('/api/catalog/products')
  const counterparties = useCount('/api/catalog/counterparties')
  const stores = useCount('/api/catalog/stores')
  const retailPoints = useCount('/api/catalog/retail-points')

  const monthDelta = stats.data && stats.data.revenuePrevMonth > 0
    ? ((stats.data.revenueThisMonth - stats.data.revenuePrevMonth) / stats.data.revenuePrevMonth) * 100
    : null

  const hasAnySales = stats.data && stats.data.series.some((b) => b.revenue > 0)

  return (
    <div className="p-4 sm:p-6 space-y-5 sm:space-y-6 overflow-auto">
      <PageHeader
        title="Dashboard"
        description={me.data ? `Добро пожаловать, ${me.data.name}` : 'Сводка по продажам и каталогу'}
      />

      {/* KPI блок продажи */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <KpiCard
          icon={Banknote}
          label="Выручка сегодня"
          value={stats.isLoading ? '…' : `${fmtMoney(stats.data?.revenueToday ?? 0)} ₸`}
          hint={`${stats.data?.transactionsToday ?? 0} чеков`}
        />
        <KpiCard
          icon={Calendar}
          label="Выручка за месяц"
          value={stats.isLoading ? '…' : `${fmtMoney(stats.data?.revenueThisMonth ?? 0)} ₸`}
          hint={`${stats.data?.transactionsThisMonth ?? 0} чеков`}
          delta={monthDelta !== null ? { value: monthDelta, positive: monthDelta >= 0 } : undefined}
        />
        <KpiCard
          icon={Receipt}
          label="Средний чек"
          value={stats.isLoading ? '…' : `${fmtMoney(stats.data?.avgTicketThisMonth ?? 0)} ₸`}
          hint="за месяц"
        />
        <KpiCard
          icon={TrendingUp}
          label="Прошлый месяц"
          value={stats.isLoading ? '…' : `${fmtMoney(stats.data?.revenuePrevMonth ?? 0)} ₸`}
          hint="для сравнения"
        />
      </div>

      {/* График продаж */}
      <section className="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-5">
        <div className="flex items-center justify-between mb-3">
          <div>
            <h2 className="text-base font-semibold text-slate-900 dark:text-slate-100">Выручка за 30 дней</h2>
            <p className="text-xs text-slate-500 mt-0.5">Сумма продаж по дням, проведённые чеки</p>
          </div>
        </div>
        {stats.isLoading ? (
          <div className="h-72 flex items-center justify-center text-slate-400 text-sm">Загрузка…</div>
        ) : !hasAnySales ? (
          <div className="h-72 flex flex-col items-center justify-center text-slate-400 text-sm gap-2">
            <Receipt className="w-8 h-8 text-slate-300" />
            <div>Чеков пока нет.</div>
            <div className="text-xs">График появится когда появятся первые продажи.</div>
          </div>
        ) : (
          <SalesChart series={stats.data!.series} currencyCode="₸" />
        )}
      </section>

      {/* Каталог */}
      <div>
        <h2 className="text-sm font-semibold text-slate-700 dark:text-slate-300 mb-3 uppercase tracking-wide">
          Каталог
        </h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <MiniCard icon={Package} label="Товаров" value={products.data} isLoading={products.isLoading} />
          <MiniCard icon={Users} label="Контрагентов" value={counterparties.data} isLoading={counterparties.isLoading} />
          <MiniCard icon={Warehouse} label="Складов" value={stores.data} isLoading={stores.isLoading} />
          <MiniCard icon={Store} label="Точек продаж" value={retailPoints.data} isLoading={retailPoints.isLoading} />
        </div>
      </div>
    </div>
  )
}
