import { useMemo, useState } from 'react';
import { Button, Card, Center, Group, Loader, Select, Stack, TextInput } from '@mantine/core';
import { Search } from 'lucide-react';

import { PageContainer, PageHeader } from '@/components/page';
import {
  InventoryInquiryDetailModal,
  VisualEmptyState,
  WarehouseInquiryTable,
  inventoryStatusOptions,
} from '@/components/warehouses';
import {
  useAllWarehouseYards,
  useAllWarehouseZones,
  useInventoryInquiry,
  useWarehouses,
} from '@/hooks/useWarehouses';
import ListControls from '@/components/common/ListControls';
// Generic list footer — already shared by the fleet and train-scheduling lists
// despite the ruleEngine path.
import RuleEngineListFooter from '@/components/ruleEngine/RuleEngineListFooter';
import { useListControls } from '@/hooks/useListControls';
import type { InventoryInquiryFilter, InventoryInquiryResult, InventoryStatus } from '@/types/warehouse';

export default function InventoryInquiryPage() {
  const [draft, setDraft] = useState<InventoryInquiryFilter>({});
  const [applied, setApplied] = useState<InventoryInquiryFilter>({});
  const [viewResult, setViewResult] = useState<InventoryInquiryResult | null>(null);

  const warehousesQuery = useWarehouses();
  const yardsQuery = useAllWarehouseYards();
  const zonesQuery = useAllWarehouseZones();

  const { data, isFetching } = useInventoryInquiry(applied);
  const results = data ?? [];

  const controls = useListControls(results, {
    searchKeys: ['containerNumber', 'bookingReference', 'customerName', 'cargoDescription', 'locationSummary'],
    dateKey: 'arrivedAt',
  });

  const warehouseOptions = useMemo(
    () => (warehousesQuery.data ?? []).map((w) => ({ value: w.id, label: `${w.name} (${w.code})` })),
    [warehousesQuery.data],
  );
  const yardOptions = useMemo(
    () =>
      (yardsQuery.data ?? [])
        .filter((y) => !draft.warehouseId || y.warehouseId === draft.warehouseId)
        .map((y) => ({ value: y.id, label: `${y.name} (${y.code})` })),
    [draft.warehouseId, yardsQuery.data],
  );
  const zoneOptions = useMemo(
    () => {
      const visibleYardIds = new Set(
        (yardsQuery.data ?? [])
          .filter((y) => !draft.warehouseId || y.warehouseId === draft.warehouseId)
          .map((y) => y.id),
      );
      return (zonesQuery.data ?? [])
        .filter((z) => {
          if (draft.yardId) return z.yardId === draft.yardId;
          if (draft.warehouseId) return visibleYardIds.has(z.yardId);
          return true;
        })
        .map((z) => ({ value: z.id, label: `${z.name} (${z.code})` }));
    },
    [draft.warehouseId, draft.yardId, yardsQuery.data, zonesQuery.data],
  );

  const normalizeDraft = (filter: InventoryInquiryFilter): InventoryInquiryFilter => ({
    ...filter,
    bookingReference: filter.bookingReference?.trim() || undefined,
    containerNumber: filter.containerNumber?.trim() || undefined,
    cargoType: filter.cargoType?.trim() || undefined,
    goodsName: filter.goodsName?.trim() || undefined,
  });

  const runSearch = () => setApplied(normalizeDraft(draft));
  const reset = () => {
    setDraft({});
    setApplied({});
  };

  return (
    <PageContainer>
      <PageHeader
        title="Inventory Inquiry"
        subtitle="Locate any cargo, container or goods inside the warehouse network."
      />

      <Stack gap="lg" mt="sm">
        <Card withBorder radius="md" padding="lg">
          <Stack gap="md">
            <Group gap="sm" wrap="wrap">
              <TextInput
                label="Booking reference"
                placeholder="e.g. BKG-00123"
                value={draft.bookingReference ?? ''}
                onChange={(e) => { const v = e.currentTarget.value; setDraft((f) => ({ ...f, bookingReference: v || undefined })); }}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') runSearch();
                }}
                w={200}
              />
              <TextInput
                label="Container number"
                placeholder="e.g. MSKU1234567"
                value={draft.containerNumber ?? ''}
                onChange={(e) => { const v = e.currentTarget.value; setDraft((f) => ({ ...f, containerNumber: v || undefined })); }}
                w={200}
              />
              <TextInput
                label="Goods name"
                placeholder="e.g. Coffee"
                value={draft.goodsName ?? ''}
                onChange={(e) => { const v = e.currentTarget.value; setDraft((f) => ({ ...f, goodsName: v || undefined })); }}
                w={180}
              />
              <Select
                label="Warehouse"
                placeholder="Any"
                clearable
                searchable
                data={warehouseOptions}
                value={draft.warehouseId ?? null}
                onChange={(value) =>
                  setDraft((f) => ({ ...f, warehouseId: value ?? undefined, yardId: undefined, zoneId: undefined }))
                }
                w={200}
              />
              <Select
                label="Yard"
                placeholder="Any"
                clearable
                searchable
                data={yardOptions}
                value={draft.yardId ?? null}
                onChange={(value) => setDraft((f) => ({ ...f, yardId: value ?? undefined, zoneId: undefined }))}
                w={180}
              />
              <Select
                label="Zone"
                placeholder="Any"
                clearable
                searchable
                data={zoneOptions}
                value={draft.zoneId ?? null}
                onChange={(value) => setDraft((f) => ({ ...f, zoneId: value ?? undefined }))}
                w={180}
              />
              <Select
                label="Status"
                placeholder="Any"
                clearable
                data={inventoryStatusOptions}
                value={draft.status ?? null}
                onChange={(value) => setDraft((f) => ({ ...f, status: (value as InventoryStatus) ?? undefined }))}
                w={180}
              />
            </Group>

            <Group>
              <Button leftSection={<Search size={16} />} onClick={runSearch}>
                Search
              </Button>
              <Button variant="default" onClick={reset}>
                Reset
              </Button>
            </Group>
          </Stack>
        </Card>

        <Card withBorder radius="md" padding="lg">
          {isFetching ? (
            <Center py="xl">
              <Loader />
            </Center>
          ) : results.length === 0 ? (
            <VisualEmptyState
              variant="container"
              title="No items found"
              description="Adjust your filters and search to locate cargo, containers or goods across the warehouse network."
            />
          ) : (
            <>
              <ListControls
                search={controls.search}
                onSearchChange={controls.setSearch}
                searchPlaceholder="Container, booking, customer, location…"
                dateFrom={controls.dateFrom}
                onDateFromChange={controls.setDateFrom}
                dateTo={controls.dateTo}
                onDateToChange={controls.setDateTo}
                dateLabel="Arrived"
                hasFilters={controls.hasFilters}
                onReset={controls.reset}
              />
              <WarehouseInquiryTable results={controls.pagedRows} onView={setViewResult} />
              <RuleEngineListFooter
                pagination={controls.pagination}
                pageCount={controls.pageCount}
                totalCount={controls.totalCount}
                itemLabel="items"
                onPaginationChange={controls.setPagination}
              />
            </>
          )}
        </Card>
      </Stack>
      <InventoryInquiryDetailModal
        opened={Boolean(viewResult)}
        onClose={() => setViewResult(null)}
        result={viewResult}
      />
    </PageContainer>
  );
}
