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

const GROUPS = [
  { value: 'period:day',   label: 'По дням' },
  { value: 'period:week',  label: 'По неделям' },
  { value: 'period:month', label: 'По месяцам' },
  { value: 'product',      label: 'По товарам' },
  { value: 'cashier',      label: 'По кассирам' },
  { value: 'register',     label: 'По кассам' },
  { value: 'payment',      label: 'По способам оплаты' },
] as const

/** Отчёт «Продажи». Табы выбора группировки, фильтры по периоду/складу/группе,
 * экспорт в CSV/XLSX. Возвраты включены со знаком минус (фискальная отчётность). */
export function SalesReportPage() {
  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 [groupBy, setGroupBy] = useState<string>('period:day')
  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(),
      groupBy,
      ...extra,
    })
    if (storeId) p.set('storeId', storeId)
    if (productGroupId) p.set('productGroupId', productGroupId)
    return p
  }

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

  const exportFile = async (format: 'csv' | 'xlsx') => {
    const resp = await api.get(`/api/reports/sales/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] ?? `sales-report.${format}`
    document.body.appendChild(a)
    a.click()
    a.remove()
    URL.revokeObjectURL(url)
  }

  const total = rep.data?.reduce((s, r) => s + r.revenue, 0) ?? 0
  const totalTx = rep.data?.reduce((s, r) => s + r.transactions, 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">Отчёт «Продажи»</h1>
        <p className="text-xs text-slate-500 mt-1">
          Проведённые чеки за период. Возвраты включаются с минусом (netto).
        </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={groupBy} onChange={(e) => setGroupBy(e.target.value)}>
                  {GROUPS.map((g) => <option key={g.value} value={g.value}>{g.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 bg-slate-50 dark:bg-slate-800/60 text-slate-700 dark:text-slate-200">
                  Итого: <span className="font-mono font-semibold">{total.toLocaleString('ru', moneyFmt)}</span>
                </span>
                <span className="px-3 py-1.5 rounded bg-slate-50 dark:bg-slate-800/60 text-slate-700 dark:text-slate-200">
                  Чеков: <span className="font-mono font-semibold">{totalTx.toLocaleString('ru')}</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 && (
              <div className="text-sm text-slate-500 py-6 text-center">За период нет данных.</div>
            )}
            {!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">Группа</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[130px] text-right">Выручка</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[120px] text-right">Скидки</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[90px] text-right">Чеков</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[120px] text-right">Кол-во</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rep.data.map((r) => (
                      <tr key={r.key} 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">{r.label}</td>
                        <td className="py-2 px-3 text-right font-mono">{r.revenue.toLocaleString('ru', moneyFmt)}</td>
                        <td className="py-2 px-3 text-right font-mono text-slate-500">{r.discount === 0 ? '—' : r.discount.toLocaleString('ru', moneyFmt)}</td>
                        <td className="py-2 px-3 text-right font-mono text-slate-500">{r.transactions}</td>
                        <td className="py-2 px-3 text-right font-mono text-slate-500">{r.quantity.toLocaleString('ru')}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </section>
        </div>
      </div>
    </div>
  )
}
