import { useEffect, useState } from 'react';
import { Alert, Button, Group, Modal, Stack, Text } 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 { BookingSelect } from './BookingSelect';
import { extractErrorMessage } from './options';

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

export function ReserveInventoryModal({ opened, onClose, item }: ReserveInventoryModalProps) {
  const { toast } = useToast();
  const reserveMutation = useMutation(api.warehouses.reserve.mutationOptions());
  const [bookingId, setBookingId] = useState('');

  useEffect(() => {
    if (opened) setBookingId(item?.bookingId ?? '');
  }, [opened, item]);

  const handleSubmit = async () => {
    if (!item) return;
    if (!bookingId.trim()) {
      toast({ variant: 'destructive', title: 'Booking is required' });
      return;
    }
    try {
      await reserveMutation.mutateAsync({ inventoryId: item.id, bookingId: bookingId.trim() });
      toast({ title: 'Inventory reserved' });
      onClose();
    } catch (error) {
      toast({ variant: 'destructive', title: 'Reserve failed', description: extractErrorMessage(error) });
    }
  };

  return (
    <Modal opened={opened} onClose={onClose} title="Reserve inventory" centered size="md">
      <Stack gap="md">
        <Alert icon={<Info size={16} />} color="blue" variant="light">
          <Text size="sm">The booking must be in <b>PAID</b> status and the inventory must be <b>STORED</b>.</Text>
        </Alert>
        <BookingSelect label="Booking (PAID)" required statuses="PAID" value={bookingId} onChange={setBookingId} />
        <Group justify="flex-end" mt="sm">
          <Button variant="default" onClick={onClose} disabled={reserveMutation.isPending}>
            Cancel
          </Button>
          <Button onClick={handleSubmit} loading={reserveMutation.isPending}>
            Reserve
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
}
