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 { Select } from '@/components/Field'
import { api } from '@/lib/api'
import { useStores } from '@/lib/useLookups'
import type { PagedResult, MovementRow } from '@/lib/types'
import type { SortOrder } from '@/components/DataTable'

const typeLabels: Record<string, string> = {
  Initial: 'Начальный',
  Supply: 'Приёмка',
  RetailSale: 'Розн. продажа',
  WholesaleSale: 'Опт. продажа',
  CustomerReturn: 'Возврат покуп.',
  SupplierReturn: 'Возврат пост.',
  TransferOut: 'Перемещ. из',
  TransferIn: 'Перемещ. в',
  WriteOff: 'Списание',
  Enter: 'Оприходование',
  InventoryAdjustment: 'Инвентаризация',
}

export function StockMovementsPage() {
  const stores = useStores()
  const [storeId, setStoreId] = useState('')
  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/movements', { storeId, page, sortKey, sortOrder }],
    queryFn: async () => {
      const params = new URLSearchParams({ page: String(page), pageSize: '50' })
      if (storeId) params.set('storeId', storeId)
      if (sortKey) { params.set('sort', sortKey); params.set('order', sortOrder) }
      return (await api.get<PagedResult<MovementRow>>(`/api/inventory/movements?${params}`)).data
    },
    placeholderData: (prev) => prev,
  })

  return (
    <ListPageShell
      title="Движения"
      description={data ? `${data.total.toLocaleString('ru')} операций в журнале` : 'Журнал всех изменений остатков'}
      actions={
        <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>
      }
      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.id}
        sortKey={sortKey}
        sortOrder={sortOrder}
        onSortChange={setSort}
        columns={[
          { header: 'Дата', width: '160px', sortKey: 'occurredAt', cell: (r) => new Date(r.occurredAt).toLocaleString('ru') },
          { header: 'Операция', width: '160px', sortKey: 'type', cell: (r) => typeLabels[r.type] ?? r.type },
          { header: 'Товар', sortKey: 'product', 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: '180px', sortKey: 'store', cell: (r) => r.storeName },
          { header: 'Количество', width: '140px', className: 'text-right font-mono', sortKey: 'quantity', cell: (r) => (
            <span className={r.quantity > 0 ? 'text-green-700' : r.quantity < 0 ? 'text-red-600' : ''}>
              {r.quantity > 0 ? '+' : ''}{r.quantity.toLocaleString('ru', { maximumFractionDigits: 3 })}
            </span>
          )},
          { header: 'Документ', width: '200px', sortKey: 'documentType', cell: (r) => r.documentNumber ? <span className="text-slate-500">{r.documentType} · {r.documentNumber}</span> : <span className="text-slate-400">—</span> },
        ]}
        empty="Движений ещё нет."
      />
    </ListPageShell>
  )
}
