import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { ListPageShell } from '@/components/ListPageShell'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
import { SearchBar } from '@/components/SearchBar'
import { Select, Checkbox } from '@/components/Field'
import { api } from '@/lib/api'
import { useStores } from '@/lib/useLookups'
import type { PagedResult, StockRow } from '@/lib/types'
import type { SortOrder } from '@/components/DataTable'

export function StockPage() {
  const stores = useStores()
  const [storeId, setStoreId] = useState('')
  const [search, setSearch] = useState('')
  const [includeZero, setIncludeZero] = useState(false)
  const [page, setPage] = useState(1)
  const [sortKey, setSortKey] = useState<string | null>(null)
  const [sortOrder, setSortOrder] = useState<SortOrder>('asc')
  const setSort = (key: string, order: SortOrder) => { setSortKey(key); setSortOrder(order); setPage(1) }

  const { data, isLoading } = useQuery({
    queryKey: ['/api/inventory/stock', { storeId, search, includeZero, page, sortKey, sortOrder }],
    queryFn: async () => {
      const params = new URLSearchParams({ page: String(page), pageSize: '50' })
      if (storeId) params.set('storeId', storeId)
      if (search) params.set('search', search)
      if (includeZero) params.set('includeZero', 'true')
      if (sortKey) { params.set('sort', sortKey); params.set('order', sortOrder) }
      return (await api.get<PagedResult<StockRow>>(`/api/inventory/stock?${params}`)).data
    },
    placeholderData: (prev) => prev,
  })

  return (
    <ListPageShell
      title="Остатки"
      description={data ? `${data.total.toLocaleString('ru')} позиций${storeId ? ' на выбранном складе' : ' по всем складам'}` : 'Текущие остатки по складам'}
      actions={
        <div className="flex items-center gap-3">
          <div className="w-52">
            <Select value={storeId} onChange={(e) => { setStoreId(e.target.value); setPage(1) }}>
              <option value="">Все склады</option>
              {stores.data?.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
            </Select>
          </div>
          <Checkbox label="Показать нулевые" checked={includeZero} onChange={(v) => { setIncludeZero(v); setPage(1) }} />
          <SearchBar value={search} onChange={(v) => { setSearch(v); setPage(1) }} placeholder="По названию или артикулу…" />
        </div>
      }
      footer={data && data.total > 0 && (
        <Pagination page={page} pageSize={data.pageSize} total={data.total} onPageChange={setPage} />
      )}
    >
      <DataTable
        rows={data?.items ?? []}
        isLoading={isLoading}
        rowKey={(r) => `${r.productId}:${r.storeId}`}
        sortKey={sortKey}
        sortOrder={sortOrder}
        onSortChange={setSort}
        columns={[
          { header: 'Товар', sortKey: 'name', cell: (r) => (
            <div>
              <div className="font-medium">{r.productName}</div>
              {r.article && <div className="text-xs text-slate-400 font-mono">{r.article}</div>}
            </div>
          )},
          { header: 'Склад', width: '220px', sortKey: 'store', cell: (r) => r.storeName },
          { header: 'Ед.', width: '80px', sortKey: 'unit', cell: (r) => r.unitName },
          { header: 'Остаток', width: '130px', className: 'text-right font-mono', sortKey: 'quantity', cell: (r) => r.quantity.toLocaleString('ru', { maximumFractionDigits: 3 }) },
          { header: 'Резерв', width: '110px', className: 'text-right font-mono text-slate-400', sortKey: 'reserved', cell: (r) => r.reservedQuantity ? r.reservedQuantity.toLocaleString('ru') : '—' },
          { header: 'Доступно', width: '130px', className: 'text-right font-mono font-semibold', sortKey: 'available', cell: (r) => (
            <span className={r.available < 0 ? 'text-red-600' : r.available === 0 ? 'text-slate-400' : ''}>
              {r.available.toLocaleString('ru', { maximumFractionDigits: 3 })}
            </span>
          )},
        ]}
        empty="Остатков нет. Они появятся после первой приёмки (Phase 2b)."
      />
    </ListPageShell>
  )
}
