import { useEffect, useMemo, useState } from 'react';
import { Alert, Button, Group, Modal, Select, Stack, Text } from '@mantine/core';
import { Info } from 'lucide-react';

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

import { api } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import type { WarehouseInventoryItem } from '@/types/warehouse';
import { extractErrorMessage } from './options';

interface StoreInventoryModalProps {
  opened: boolean;
  onClose: () => void;
  item: WarehouseInventoryItem | null;
}

/**
 * Store an unloaded import item. The operator may pick warehouse → yard → zone
 * explicitly; leaving them blank falls back to the backend auto allocation.
 */
export function StoreInventoryModal({ opened, onClose, item }: StoreInventoryModalProps) {
  const { toast } = useToast();
  const storeMutation = useMutation(api.warehouses.store.mutationOptions());
  const [warehouseId, setWarehouseId] = useState('');
  const [yardId, setYardId] = useState('');
  const [zoneId, setZoneId] = useState('');

  useEffect(() => {
    if (opened) {
      setWarehouseId('');
      setYardId('');
      setZoneId('');
    }
  }, [opened]);

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

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

  const isManual = Boolean(warehouseId || yardId || zoneId);
  const manualComplete = Boolean(warehouseId && yardId && zoneId);

  const handleSubmit = async () => {
    if (!item) return;
    if (isManual && !manualComplete) {
      toast({ variant: 'destructive', title: 'Pick warehouse, yard and zone — or clear all to auto-allocate' });
      return;
    }
    try {
      await storeMutation.mutateAsync({
        id: item.id,
        payload: manualComplete ? { warehouseId, yardId, zoneId } : undefined,
      });
      toast({ title: manualComplete ? 'Inventory stored at selected location' : 'Inventory stored (auto-allocated)' });
      onClose();
    } catch (error) {
      toast({ variant: 'destructive', title: 'Store failed', description: extractErrorMessage(error) });
    }
  };

  return (
    <Modal opened={opened} onClose={onClose} title="Store inventory" centered size="lg">
      <Stack gap="md">
        <Alert icon={<Info size={16} />} color="blue" variant="light">
          <Text size="sm">
            Choose a warehouse, yard and zone to store this item at a specific location, or leave them
            blank to let the system auto-allocate by rule / available capacity.
          </Text>
        </Alert>
        <Select
          label="Warehouse"
          placeholder="Auto-allocate"
          searchable
          clearable
          data={warehouseOptions}
          value={warehouseId || null}
          onChange={(v) => {
            setWarehouseId(v ?? '');
            setYardId('');
            setZoneId('');
          }}
        />
        <Select
          label="Yard"
          placeholder={!warehouseId ? 'Select a warehouse first' : 'Select yard'}
          searchable
          clearable
          disabled={!warehouseId}
          data={yardOptions}
          value={yardId || null}
          onChange={(v) => {
            setYardId(v ?? '');
            setZoneId('');
          }}
        />
        <Select
          label="Zone"
          placeholder={!yardId ? 'Select a yard first' : 'Select zone'}
          searchable
          clearable
          disabled={!yardId}
          data={zoneOptions}
          value={zoneId || null}
          onChange={(v) => setZoneId(v ?? '')}
        />
        <Group justify="flex-end" mt="sm">
          <Button variant="default" onClick={onClose} disabled={storeMutation.isPending}>
            Cancel
          </Button>
          <Button onClick={handleSubmit} loading={storeMutation.isPending}>
            {manualComplete ? 'Store here' : 'Store (auto)'}
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
}
