import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Download, BarChart3 } from 'lucide-react'
import { api } from '@/lib/api'
import { Button } from '@/components/Button'
import { EmptyState } from '@/components/EmptyState'
import { Field, Select } from '@/components/Field'
import { DateField } from '@/components/DateField'
import { useStores, useProductGroups } from '@/lib/useLookups'
import { useOrgSettings } from '@/lib/useOrgSettings'
import { type AbcReportRow } from '@/lib/types'

const METRICS = [
  { value: 'revenue', label: 'Выручка' },
  { value: 'profit',  label: 'Прибыль' },
  { value: 'margin',  label: 'Маржа' },
] as const

const CLASS_COLOR: Record<string, string> = {
  A: 'bg-green-100 text-green-800',
  B: 'bg-yellow-100 text-yellow-800',
  C: 'bg-red-100 text-red-800',
}

/** ABC-анализ. Топ-товары по выручке/прибыли/марже с распределением по
 * классам Парето (80/15/5). Визуализация — цветные плашки класса и
 * полоса накопительной доли. */
export function AbcReportPage() {
  const todayIso = () => new Date().toISOString().slice(0, 10)
  const monthAgoIso = () => {
    const d = new Date(); d.setDate(d.getDate() - 30)
    return d.toISOString().slice(0, 10)
  }

  const [from, setFrom] = useState<string>(monthAgoIso())
  const [to, setTo] = useState<string>(todayIso())
  const [metric, setMetric] = useState<string>('revenue')
  const [storeId, setStoreId] = useState<string>('')
  const [productGroupId, setProductGroupId] = useState<string>('')

  const stores = useStores()
  const groups = useProductGroups()
  const org = useOrgSettings()
  const fractional = org.data?.allowFractionalPrices ?? false
  const moneyFmt = fractional
    ? { minimumFractionDigits: 2, maximumFractionDigits: 2 }
    : { maximumFractionDigits: 0 }

  const params = (extra: Record<string, string> = {}) => {
    const p = new URLSearchParams({
      from: new Date(from).toISOString(),
      to: new Date(`${to}T23:59:59`).toISOString(),
      metric,
      ...extra,
    })
    if (storeId) p.set('storeId', storeId)
    if (productGroupId) p.set('productGroupId', productGroupId)
    return p
  }

  const rep = useQuery({
    queryKey: ['abc-report', from, to, metric, storeId, productGroupId],
    queryFn: async () => (await api.get<AbcReportRow[]>(`/api/reports/abc?${params()}`)).data,
  })

  const exportFile = async (format: 'csv' | 'xlsx') => {
    const resp = await api.get(`/api/reports/abc/export?${params({ format })}`, { responseType: 'blob' })
    const blob = new Blob([resp.data])
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    const cd = resp.headers['content-disposition'] as string | undefined
    const match = cd?.match(/filename="?([^";]+)"?/i)
    a.download = match?.[1] ?? `abc-report.${format}`
    document.body.appendChild(a)
    a.click()
    a.remove()
    URL.revokeObjectURL(url)
  }

  const counts = { A: 0, B: 0, C: 0 } as Record<string, number>
  rep.data?.forEach((r) => { counts[r.abcClass] = (counts[r.abcClass] ?? 0) + 1 })
  const total = rep.data?.length ?? 0
  const totalValue = rep.data?.reduce((s, r) => s + r.metricValue, 0) ?? 0

  return (
    <div className="flex flex-col h-full">
      <div className="px-6 py-4 border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900">
        <h1 className="text-lg font-semibold text-slate-900 dark:text-slate-100">Отчёт «ABC-анализ»</h1>
        <p className="text-xs text-slate-500 mt-1">
          Топ-товары по выбранной метрике с разбиением A/B/C по правилу Парето (80/15/5).
        </p>
      </div>
      <div className="flex-1 overflow-auto">
        <div className="max-w-6xl mx-auto p-3 sm:p-6 space-y-4">
          <section className="bg-white dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-800 p-4">
            <div className="grid grid-cols-1 md:grid-cols-5 gap-x-4 gap-y-3 items-end">
              <Field label="От">
                <DateField value={from} onChange={(v) => setFrom(v ?? todayIso())} />
              </Field>
              <Field label="До">
                <DateField value={to} onChange={(v) => setTo(v ?? todayIso())} />
              </Field>
              <Field label="Метрика">
                <Select value={metric} onChange={(e) => setMetric(e.target.value)}>
                  {METRICS.map((m) => <option key={m.value} value={m.value}>{m.label}</option>)}
                </Select>
              </Field>
              <Field label="Склад">
                <Select value={storeId} onChange={(e) => setStoreId(e.target.value)}>
                  <option value="">Все</option>
                  {stores.data?.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
                </Select>
              </Field>
              <Field label="Группа товаров">
                <Select value={productGroupId} onChange={(e) => setProductGroupId(e.target.value)}>
                  <option value="">Все</option>
                  {groups.data?.map((g) => <option key={g.id} value={g.id}>{g.name}</option>)}
                </Select>
              </Field>
            </div>
            <div className="mt-4 flex flex-wrap gap-3 items-center justify-between">
              <div className="flex gap-2 text-sm">
                <span className={`px-3 py-1.5 rounded ${CLASS_COLOR.A}`}>A: {counts.A ?? 0}</span>
                <span className={`px-3 py-1.5 rounded ${CLASS_COLOR.B}`}>B: {counts.B ?? 0}</span>
                <span className={`px-3 py-1.5 rounded ${CLASS_COLOR.C}`}>C: {counts.C ?? 0}</span>
                <span className="px-3 py-1.5 rounded bg-slate-50 dark:bg-slate-800/60">
                  Всего: {total} · итог метрики: <span className="font-mono font-semibold">{totalValue.toLocaleString('ru', moneyFmt)}</span>
                </span>
              </div>
              <div className="flex gap-2">
                <Button type="button" variant="secondary" size="sm" onClick={() => exportFile('csv')}>
                  <Download className="w-4 h-4" /> CSV
                </Button>
                <Button type="button" variant="secondary" size="sm" onClick={() => exportFile('xlsx')}>
                  <Download className="w-4 h-4" /> XLSX
                </Button>
              </div>
            </div>
          </section>

          <section className="bg-white dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-800 p-4">
            {rep.isLoading && <div className="text-sm text-slate-500 py-6 text-center">Загружаю…</div>}
            {!rep.isLoading && (rep.data?.length ?? 0) === 0 && (
              <EmptyState
                icon={BarChart3}
                title="Данных для ABC-анализа нет"
                description="Анализ запускается по периоду продаж — пока их недостаточно, классы не построятся."
              />
            )}
            {!rep.isLoading && rep.data && rep.data.length > 0 && (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="text-left">
                    <tr className="border-b border-slate-200 dark:border-slate-700">
                      <th className="py-2 pr-3 font-medium text-xs uppercase text-slate-500 w-[60px]">Ранг</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[60px]">Класс</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500">Товар</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[110px]">Артикул</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[150px] text-right">Метрика</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[100px] text-right">Доля,%</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[200px]">Накопит.</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rep.data.map((r) => (
                      <tr key={r.productId} className="border-b border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/30">
                        <td className="py-2 pr-3 text-slate-500">{r.rank}</td>
                        <td className="py-2 px-3">
                          <span className={`inline-block w-6 h-6 rounded text-center text-xs font-semibold leading-6 ${CLASS_COLOR[r.abcClass] ?? 'bg-slate-100 text-slate-700'}`}>{r.abcClass}</span>
                        </td>
                        <td className="py-2 px-3">{r.productName}</td>
                        <td className="py-2 px-3 text-slate-500">{r.productArticle ?? '—'}</td>
                        <td className="py-2 px-3 text-right font-mono">{r.metricValue.toLocaleString('ru', moneyFmt)}</td>
                        <td className="py-2 px-3 text-right font-mono text-slate-500">{r.share.toFixed(2)}</td>
                        <td className="py-2 px-3">
                          <div className="flex items-center gap-2">
                            <div className="flex-1 h-2 bg-slate-100 dark:bg-slate-800 rounded overflow-hidden">
                              <div
                                className={r.abcClass === 'A' ? 'bg-green-500' : r.abcClass === 'B' ? 'bg-yellow-500' : 'bg-red-500'}
                                style={{ width: `${Math.min(100, r.cumulativeShare)}%`, height: '100%' }}
                              />
                            </div>
                            <span className="font-mono text-xs text-slate-500 w-[55px] text-right">{r.cumulativeShare.toFixed(1)}%</span>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </section>
        </div>
      </div>
    </div>
  )
}
