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

/** Отчёт «Остатки на дату». Реконструкция через журнал StockMovement. */
export function StockReportPage() {
  const today = new Date().toISOString().slice(0, 10)
  const [date, setDate] = useState<string>(today)
  const [storeId, setStoreId] = useState<string>('')
  const [productGroupId, setProductGroupId] = useState<string>('')
  const [includeZero, setIncludeZero] = useState<boolean>(false)

  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({
      date: new Date(`${date}T23:59:59`).toISOString(),
      ...extra,
    })
    if (storeId) p.set('storeId', storeId)
    if (productGroupId) p.set('productGroupId', productGroupId)
    if (includeZero) p.set('includeZero', 'true')
    return p
  }

  const rep = useQuery({
    queryKey: ['stock-report', date, storeId, productGroupId, includeZero],
    queryFn: async () => (await api.get<StockReportRow[]>(`/api/reports/stock?${params()}`)).data,
  })

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

  const total = rep.data?.reduce((s, r) => s + r.value, 0) ?? 0
  const items = rep.data?.length ?? 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">
          Реконструкция через журнал движений. Стоимость — последний UnitCost
          движения; если в журнале нет — Product.Cost (приближённая оценка).
        </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-4 gap-x-4 gap-y-3 items-end">
              <Field label="На дату">
                <DateField value={date} onChange={(v) => setDate(v ?? today)} />
              </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>
              <Field label=" ">
                <Checkbox label="Показывать нулевые остатки" checked={includeZero} onChange={setIncludeZero} />
              </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">
                  Позиций: <span className="font-mono font-semibold">{items.toLocaleString('ru')}</span>
                </span>
                <span className="px-3 py-1.5 rounded bg-slate-50 dark:bg-slate-800/60">
                  Стоимость: <span className="font-mono font-semibold">{total.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={Warehouse}
                title="Остатки пусты"
                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">Товар</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[100px]">Артикул</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[80px]">Ед.</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[180px]">Склад</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-[120px] text-right">Цена</th>
                      <th className="py-2 px-3 font-medium text-xs uppercase text-slate-500 w-[140px] text-right">Стоимость</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rep.data.map((r) => (
                      <tr key={`${r.productId}-${r.storeId}`} 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.productName}</td>
                        <td className="py-2 px-3 text-slate-500">{r.productArticle ?? '—'}</td>
                        <td className="py-2 px-3 text-slate-500">{r.unitName ?? '—'}</td>
                        <td className="py-2 px-3 text-slate-500">{r.storeName}</td>
                        <td className="py-2 px-3 text-right font-mono">{r.quantity.toLocaleString('ru')}</td>
                        <td className="py-2 px-3 text-right font-mono text-slate-500">{r.cost.toLocaleString('ru', moneyFmt)}</td>
                        <td className="py-2 px-3 text-right font-mono">{r.value.toLocaleString('ru', moneyFmt)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </section>
        </div>
      </div>
    </div>
  )
}
