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 { useQuery } from '@tanstack/react-query';

import { VisualEmptyState, WarehouseInquiryTable, inventoryStatusOptions } from '@/components/warehouses';
import { api } from '@/services/api';
import type { InventoryInquiryFilter, InventoryStatus } from '@/types/warehouse';

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

  const warehousesQuery = useQuery(
    api.warehouses.list.queryOptions({ input: {} }),
  );
  const yardsQuery = useQuery(
    api.warehouses.listYards.queryOptions({
      input: { warehouseId: draft.warehouseId ?? '' },
      enabled: Boolean(draft.warehouseId),
    }),
  );
  const zonesQuery = useQuery(
    api.warehouses.listZones.queryOptions({
      input: { yardId: draft.yardId ?? '' },
      enabled: Boolean(draft.yardId),
    }),
  );

  const { data, isFetching } = useQuery(
    api.warehouses.inquiry.queryOptions({ input: { filter: applied } }),
  );
  const results = data ?? [];

  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],
  );

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

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

      <Card>
        <Stack gap="md">
          <Group gap="sm" wrap="wrap">
            <TextInput
              label="Booking number"
              placeholder="e.g. BKG-00123"
              value={draft.bookingNumber ?? ''}
              onChange={(e) => { const v = e.currentTarget.value; setDraft((f) => ({ ...f, bookingNumber: v || undefined })); }}
              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
              disabled={!draft.warehouseId}
              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
              disabled={!draft.yardId}
              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>
        {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."
          />
        ) : (
          <WarehouseInquiryTable results={results} />
        )}
      </Card>
    </PageContainer>
  );
}
