import { useState } from 'react';
import { Button, Center, Group, Loader, Stack, Text } from '@mantine/core';
import { ClipboardCheck } from 'lucide-react';

import { useMutation } from '@tanstack/react-query';

import { api } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import type { InventoryAction, WarehouseInventoryItem } from '@/types/warehouse';
import { DeliverInventoryModal } from './DeliverInventoryModal';
import { FeePreviewModal } from './FeePreviewModal';
import { InspectionReportModal } from './InspectionReportModal';
import { InventoryHistoryModal } from './InventoryHistoryModal';
import { LoadInventoryModal } from './LoadInventoryModal';
import { MoveInventoryModal } from './MoveInventoryModal';
import { ReleaseOrderModal } from './ReleaseOrderModal';
import { ReserveInventoryModal } from './ReserveInventoryModal';
import { WarehouseInventoryTable } from './WarehouseInventoryTable';
import { extractErrorMessage } from './options';

interface InventoryWorkbenchProps {
  items: WarehouseInventoryItem[];
  isLoading?: boolean;
  /** Optional Last Mile action (Batch 8) — only shown for items whose booking requested door delivery. */
  onLastMile?: (item: WarehouseInventoryItem) => void;
}

/** Inventory table + all lifecycle actions (advance / move / reserve / history). */
export function InventoryWorkbench({ items, isLoading, onLastMile }: InventoryWorkbenchProps) {
  const { toast } = useToast();
  const [busyId, setBusyId] = useState<string | null>(null);
  const [moveItem, setMoveItem] = useState<WarehouseInventoryItem | null>(null);
  const [reserveItem, setReserveItem] = useState<WarehouseInventoryItem | null>(null);
  const [loadItem, setLoadItem] = useState<WarehouseInventoryItem | null>(null);
  const [historyItem, setHistoryItem] = useState<WarehouseInventoryItem | null>(null);
  const [inspectItem, setInspectItem] = useState<WarehouseInventoryItem | null>(null);
  const [feeItem, setFeeItem] = useState<WarehouseInventoryItem | null>(null);
  const [releaseItem, setReleaseItem] = useState<WarehouseInventoryItem | null>(null);
  const [deliverItem, setDeliverItem] = useState<WarehouseInventoryItem | null>(null);

  const storeMutation = useMutation(api.warehouses.store.mutationOptions());
  const readyMutation = useMutation(
    api.warehouses.markReadyForLoading.mutationOptions(),
  );
  const pickupMutation = useMutation(
    api.warehouses.markReadyForPickup.mutationOptions(),
  );
  const dispatchMutation = useMutation(api.warehouses.dispatch.mutationOptions());
  const inspectMutation = useMutation(
    api.warehouses.bulkMarkInspected.mutationOptions(),
  );

  const [selected, setSelected] = useState<Set<string>>(new Set());
  const allSelected = items.length > 0 && selected.size === items.length;
  const someSelected = selected.size > 0 && !allSelected;
  const toggleSelect = (id: string) =>
    setSelected((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  const toggleSelectAll = () =>
    setSelected(allSelected ? new Set() : new Set(items.map((i) => i.id)));

  const markInspected = async () => {
    if (selected.size === 0) {
      toast({ variant: 'destructive', title: 'Select at least one item' });
      return;
    }
    try {
      const r = await inspectMutation.mutateAsync({ inventoryIds: [...selected] });
      toast({
        title: `${r.inspectedCount} marked inspected`,
        description: r.skippedCount ? `${r.skippedCount} skipped` : undefined,
      });
      setSelected(new Set());
    } catch (error) {
      toast({ variant: 'destructive', title: 'Mark inspected failed', description: extractErrorMessage(error) });
    }
  };

  const runDirect = async (item: WarehouseInventoryItem, fn: () => Promise<unknown>, label: string) => {
    setBusyId(item.id);
    try {
      await fn();
      toast({ title: label });
    } catch (error) {
      toast({ variant: 'destructive', title: 'Action failed', description: extractErrorMessage(error) });
    } finally {
      setBusyId(null);
    }
  };

  const advance = (item: WarehouseInventoryItem, action: InventoryAction) => {
    switch (action) {
      case 'store':
        return runDirect(item, () => storeMutation.mutateAsync(item.id), 'Inventory stored');
      case 'reserve':
        setReserveItem(item);
        return;
      case 'ready-for-loading':
        return runDirect(item, () => readyMutation.mutateAsync(item.id), 'Ready for loading');
      case 'load':
        setLoadItem(item);
        return;
      case 'dispatch':
        return runDirect(item, () => dispatchMutation.mutateAsync(item.id), 'Inventory dispatched');
      case 'ready-for-pickup':
        return runDirect(item, () => pickupMutation.mutateAsync(item.id), 'Ready for pickup');
      case 'release':
        setReleaseItem(item);
        return;
      case 'deliver':
        setDeliverItem(item);
        return;
      default:
        return;
    }
  };

  if (isLoading) {
    return (
      <Center py="xl">
        <Loader />
      </Center>
    );
  }

  return (
    <>
      <Stack gap="sm">
        <Group justify="space-between">
          <Text size="sm" c="dimmed">
            Selected: <b>{selected.size}</b>
          </Text>
          <Button
            size="compact-sm"
            variant="light"
            leftSection={<ClipboardCheck size={14} />}
            disabled={selected.size === 0}
            loading={inspectMutation.isPending}
            onClick={markInspected}
          >
            Mark Selected as Inspected
          </Button>
        </Group>

        <WarehouseInventoryTable
          items={items}
          busyId={busyId}
          onAdvance={advance}
          onMove={setMoveItem}
          onHistory={setHistoryItem}
          onInspect={setInspectItem}
          onFeePreview={setFeeItem}
          onLastMile={onLastMile}
          selectedIds={selected}
          onToggleSelect={toggleSelect}
          onToggleSelectAll={toggleSelectAll}
          allSelected={allSelected}
          someSelected={someSelected}
        />
      </Stack>

      <MoveInventoryModal opened={Boolean(moveItem)} onClose={() => setMoveItem(null)} item={moveItem} />
      <ReserveInventoryModal
        opened={Boolean(reserveItem)}
        onClose={() => setReserveItem(null)}
        item={reserveItem}
      />
      <LoadInventoryModal opened={Boolean(loadItem)} onClose={() => setLoadItem(null)} item={loadItem} />
      <InventoryHistoryModal
        opened={Boolean(historyItem)}
        onClose={() => setHistoryItem(null)}
        item={historyItem}
      />
      <InspectionReportModal
        opened={Boolean(inspectItem)}
        onClose={() => setInspectItem(null)}
        inventoryId={inspectItem?.id ?? null}
      />
      <FeePreviewModal
        opened={Boolean(feeItem)}
        onClose={() => setFeeItem(null)}
        inventoryId={feeItem?.id ?? null}
      />
      <ReleaseOrderModal opened={Boolean(releaseItem)} onClose={() => setReleaseItem(null)} item={releaseItem} />
      <DeliverInventoryModal opened={Boolean(deliverItem)} onClose={() => setDeliverItem(null)} item={deliverItem} />
    </>
  );
}
