import { useRef } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { Plus, Trash2 } from 'lucide-react'
import { ListPageShell } from '@/components/ListPageShell'
import { DataTable } from '@/components/DataTable'
import { EmptyState } from '@/components/EmptyState'
import { Pagination } from '@/components/Pagination'
import { SearchBar } from '@/components/SearchBar'
import { Button } from '@/components/Button'
import { useCatalogList } from '@/lib/useCatalog'
import { useShortcuts } from '@/lib/useShortcuts'
import { useOrgSettings } from '@/lib/useOrgSettings'
import { type LossListRow, LossStatus, lossReasonLabel } from '@/lib/types'

const URL = '/api/inventory/losses'

export function LossesPage() {
  const navigate = useNavigate()
  const { data, isLoading, page, setPage, search, setSearch, sortKey, sortOrder, setSort } = useCatalogList<LossListRow>(URL)
  const org = useOrgSettings()
  const fractional = org.data?.allowFractionalPrices ?? false
  const moneyFmt = fractional
    ? { minimumFractionDigits: 2, maximumFractionDigits: 2 }
    : { maximumFractionDigits: 0 }
  const searchRef = useRef<HTMLInputElement>(null)

  // Хоткеи list-страницы: `/` фокусит поиск, `n` — создать новое списание.
  useShortcuts({
    '/': () => searchRef.current?.focus(),
    'n': () => navigate('/inventory/losses/new'),
  })

  return (
    <ListPageShell
      title="Списания"
      description={data ? `${data.total.toLocaleString('ru')} документов` : 'Брак, просрочка, повреждения, недостача.'}
      actions={
        <>
          <SearchBar ref={searchRef} value={search} onChange={setSearch} placeholder="По номеру…" />
          <Link to="/inventory/losses/new">
            <Button><Plus className="w-4 h-4" /> Новое списание</Button>
          </Link>
        </>
      }
      footer={data && data.total > 0 && (
        <Pagination page={page} pageSize={data.pageSize} total={data.total} onPageChange={setPage} />
      )}
    >
      {!isLoading && (data?.items?.length ?? 0) === 0 && !search ? (
        <EmptyState
          icon={Trash2}
          title="Списаний пока нет"
          description="Списания фиксируют выбытие товаров (просрочка, брак, потери)."
          actionLabel="Создать списание"
          onAction={() => navigate('/inventory/losses/new')}
        />
      ) : (
        <DataTable
          rows={data?.items ?? []}
          isLoading={isLoading}
          rowKey={(r) => r.id}
          sortKey={sortKey}
          sortOrder={sortOrder}
          onSortChange={setSort}
          onRowClick={(r) => navigate(`/inventory/losses/${r.id}`)}
          columns={[
            { header: '№', width: '160px', sortKey: 'number', cell: (r) => <span className="font-mono text-slate-600">{r.number}</span> },
            { header: 'Дата', width: '120px', sortKey: 'date', cell: (r) => new Date(r.date).toLocaleDateString('ru') },
            { header: 'Статус', width: '110px', sortKey: 'status', cell: (r) => (
              r.status === LossStatus.Posted
                ? <span className="text-xs px-2 py-0.5 rounded bg-green-50 text-green-700">Проведён</span>
                : <span className="text-xs px-2 py-0.5 rounded bg-slate-100 text-slate-600">Черновик</span>
            )},
            { header: 'Причина', width: '140px', sortKey: 'reason', cell: (r) => lossReasonLabel[r.reason] ?? r.reason },
            { header: 'Склад', sortKey: 'store', cell: (r) => r.storeName },
            { header: 'Позиций', width: '90px', className: 'text-right', cell: (r) => r.lineCount },
            { header: 'Сумма', width: '160px', className: 'text-right font-mono', sortKey: 'total', cell: (r) => `${r.total.toLocaleString('ru', moneyFmt)} ${r.currencyCode}` },
          ]}
          empty="Списаний пока нет."
        />
      )}
    </ListPageShell>
  )
}
