import { useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Card, Group, Select, Stack, TextInput } from '@mantine/core';
import { useDebouncedValue } from '@mantine/hooks';
import { PackageOpen, Search, Truck, X } from 'lucide-react';

import { PageContainer, PageHeader } from '@/components/page';
import {
  InventoryWorkbench,
  inventoryStatusOptions,
} from '@/components/warehouses';
import {
  useWarehouseInventory,
  useWarehouseYards,
  useWarehouseZones,
  useWarehouses,
} from '@/hooks/useWarehouses';
import type { InventoryFilter, InventoryStatus } from '@/types/warehouse';

export default function WarehouseInventoryPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const initialStatus = (searchParams.get('status') as InventoryStatus | null) ?? undefined;
  const direction = (searchParams.get('direction') as 'IMPORT' | 'EXPORT' | null) ?? undefined;
  const [filter, setFilter] = useState<InventoryFilter>(
    initialStatus ? { status: initialStatus } : {},
  );
  // KPI drill-downs arriving from the ops dashboard cards; each shows as a
  // dismissible chip so the list can be widened back out in place.
  const [quick, setQuick] = useState<
    Pick<InventoryFilter, 'receivedToday' | 'pendingInspection' | 'agingOverDays'>
  >(() => {
    const aging = Number(searchParams.get('agingOverDays'));
    return {
      receivedToday: searchParams.get('receivedToday') ? true : undefined,
      pendingInspection: searchParams.get('pendingInspection') ? true : undefined,
      agingOverDays: Number.isFinite(aging) && aging > 0 ? aging : undefined,
    };
  });
  const [search, setSearch] = useState('');

  const [debouncedSearch] = useDebouncedValue(search, 300);
  const queryFilter = useMemo<InventoryFilter>(
    () => ({ ...filter, ...quick, direction, search: debouncedSearch || undefined }),
    [filter, quick, direction, debouncedSearch],
  );

  const quickChips: Array<{ key: keyof typeof quick; label: string }> = [
    ...(quick.receivedToday ? [{ key: 'receivedToday' as const, label: 'Received today' }] : []),
    ...(quick.pendingInspection
      ? [{ key: 'pendingInspection' as const, label: 'Pending inspection' }]
      : []),
    ...(quick.agingOverDays
      ? [{ key: 'agingOverDays' as const, label: `In warehouse >${quick.agingOverDays}d` }]
      : []),
  ];

  const warehousesQuery = useWarehouses();
  const yardsQuery = useWarehouseYards(filter.warehouseId);
  const zonesQuery = useWarehouseZones(filter.yardId);
  const inventoryQuery = useWarehouseInventory(queryFilter);

  const warehouseOptions = useMemo(
    () => (warehousesQuery.data ?? []).map((w) => ({ value: w.id, label: `${w.name} (${w.code})` })),
    [warehousesQuery.data],
  );
  const yardOptions = useMemo(
    () => (yardsQuery.data ?? []).map((y) => ({ value: y.id, label: `${y.name} (${y.code})` })),
    [yardsQuery.data],
  );
  const zoneOptions = useMemo(
    () => (zonesQuery.data ?? []).map((z) => ({ value: z.id, label: `${z.name} (${z.code})` })),
    [zonesQuery.data],
  );

  return (
    <PageContainer>
      <PageHeader
        title={
          direction === 'IMPORT'
            ? 'Import Terminal Inventory'
            : direction === 'EXPORT'
              ? 'Export Terminal Inventory'
              : 'Warehouse Inventory'
        }
        subtitle="Track received items through the storage, reservation, loading and dispatch lifecycle."
        action={
          <Group gap="xs">
            <Button
              variant="light"
              leftSection={<PackageOpen size={16} />}
              onClick={() => navigate('/dashboard/import-warehouse')}
            >
              Import
            </Button>
            <Button leftSection={<Truck size={16} />} onClick={() => navigate('/dashboard/export-warehouse')}>
              Export
            </Button>
          </Group>
        }
      />

      <Card>
        <Stack gap="md">
          <Group gap="sm" wrap="wrap">
            <TextInput
              placeholder="Search notes"
              leftSection={<Search size={16} />}
              value={search}
              onChange={(e) => setSearch(e.currentTarget.value)}
              w={220}
            />
            <Select
              placeholder="All warehouses"
              clearable
              searchable
              data={warehouseOptions}
              value={filter.warehouseId ?? null}
              onChange={(value) =>
                setFilter((f) => ({
                  ...f,
                  warehouseId: value ?? undefined,
                  yardId: undefined,
                  zoneId: undefined,
                }))
              }
              w={220}
            />
            <Select
              placeholder="All yards"
              clearable
              searchable
              disabled={!filter.warehouseId}
              data={yardOptions}
              value={filter.yardId ?? null}
              onChange={(value) =>
                setFilter((f) => ({ ...f, yardId: value ?? undefined, zoneId: undefined }))
              }
              w={200}
            />
            <Select
              placeholder="All zones"
              clearable
              searchable
              disabled={!filter.yardId}
              data={zoneOptions}
              value={filter.zoneId ?? null}
              onChange={(value) => setFilter((f) => ({ ...f, zoneId: value ?? undefined }))}
              w={200}
            />
            <Select
              placeholder="All statuses"
              clearable
              data={inventoryStatusOptions}
              value={filter.status ?? null}
              onChange={(value) =>
                setFilter((f) => ({ ...f, status: (value as InventoryStatus) ?? undefined }))
              }
              w={200}
            />
            {quickChips.map((chip) => (
              <Button
                key={chip.key}
                size="compact-xs"
                variant="light"
                rightSection={<X size={12} />}
                onClick={() => setQuick((q) => ({ ...q, [chip.key]: undefined }))}
              >
                {chip.label}
              </Button>
            ))}
          </Group>

          <InventoryWorkbench items={inventoryQuery.data ?? []} isLoading={inventoryQuery.isLoading} />
        </Stack>
      </Card>
    </PageContainer>
  );
}
