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

import { PageContainer, PageHeader } from '@/components/page';
import {
  InventoryWorkbench,
  ReceiveInventoryModal,
  inventoryStatusOptions,
} from '@/components/warehouses';
import { useQuery } from '@tanstack/react-query';

import { api } from '@/services/api';
import type { InventoryFilter, InventoryStatus } from '@/types/warehouse';

export default function WarehouseInventoryPage() {
  const [searchParams] = useSearchParams();
  const initialStatus = (searchParams.get('status') as InventoryStatus | null) ?? undefined;
  const [filter, setFilter] = useState<InventoryFilter>(
    initialStatus ? { status: initialStatus } : {},
  );
  const [search, setSearch] = useState('');
  const [modalOpen, setModalOpen] = useState(false);

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

  const warehousesQuery = useQuery(
    api.warehouses.list.queryOptions({ input: {} }),
  );
  const yardsQuery = useQuery(
    api.warehouses.listYards.queryOptions({
      input: { warehouseId: filter.warehouseId ?? '' },
      enabled: Boolean(filter.warehouseId),
    }),
  );
  const zonesQuery = useQuery(
    api.warehouses.listZones.queryOptions({
      input: { yardId: filter.yardId ?? '' },
      enabled: Boolean(filter.yardId),
    }),
  );
  const inventoryQuery = useQuery(
    api.warehouses.listInventory.queryOptions({ input: { filter: 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="Warehouse Inventory"
        subtitle="Track received items through the storage, reservation, loading and dispatch lifecycle."
        action={
          <Button leftSection={<PackagePlus size={16} />} onClick={() => setModalOpen(true)}>
            Receive Inventory
          </Button>
        }
      />

      <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}
            />
          </Group>

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

      <ReceiveInventoryModal opened={modalOpen} onClose={() => setModalOpen(false)} />
    </PageContainer>
  );
}
