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

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

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

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

/** Load READY_FOR_LOADING inventory onto a wagon (creates a loading record). */
export function LoadInventoryModal({ opened, onClose, item }: LoadInventoryModalProps) {
  const { toast } = useToast();
  const loadMutation = useMutation(api.warehouses.load.mutationOptions());
  const [wagonId, setWagonId] = useState('');
  const [loadedWeight, setLoadedWeight] = useState<number | ''>('');
  const [notes, setNotes] = useState('');

  useEffect(() => {
    if (opened) {
      setWagonId('');
      setLoadedWeight(item?.weight ?? '');
      setNotes('');
    }
  }, [opened, item]);

  const handleSubmit = async () => {
    if (!item) return;
    if (!wagonId.trim()) {
      toast({ variant: 'destructive', title: 'Select a wagon' });
      return;
    }
    try {
      await loadMutation.mutateAsync({
        id: item.id,
        payload: {
          wagonId: wagonId.trim(),
          loadedWeight: loadedWeight === '' ? undefined : Number(loadedWeight),
          notes: notes.trim() || undefined,
        },
      });
      toast({ title: 'Inventory loaded', description: 'Status set to LOADED' });
      onClose();
    } catch (error) {
      toast({ variant: 'destructive', title: 'Load failed', description: extractErrorMessage(error) });
    }
  };

  return (
    <Modal opened={opened} onClose={onClose} title="Load onto wagon" centered size="md">
      <Stack gap="md">
        <Alert icon={<Info size={16} />} color="blue" variant="light">
          <Text size="sm">
            The item must be <b>READY_FOR_LOADING</b> and the wagon must be available or already on a
            train schedule.
          </Text>
        </Alert>

        <WagonSelect label="Wagon" required value={wagonId} onChange={setWagonId} />

        <NumberInput
          label="Loaded weight (kg)"
          placeholder="Defaults to item weight"
          min={0}
          value={loadedWeight}
          onChange={(v) => setLoadedWeight(v === '' ? '' : Number(v))}
        />

        <Textarea
          label="Notes"
          placeholder="Optional"
          autosize
          minRows={2}
          value={notes}
          onChange={(e) => {
            const v = e.currentTarget.value;
            setNotes(v);
          }}
        />

        <Group justify="flex-end" mt="sm">
          <Button variant="default" onClick={onClose} disabled={loadMutation.isPending}>
            Cancel
          </Button>
          <Button onClick={handleSubmit} loading={loadMutation.isPending}>
            Load
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
}
