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

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

export function ReleaseOrderModal({ opened, onClose, item }: ReleaseOrderModalProps) {
  const { toast } = useToast();
  const releaseMutation = useMutation(api.warehouses.release.mutationOptions());
  const [reference, setReference] = useState('');

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

  const handleSubmit = async () => {
    if (!item) return;
    try {
      await releaseMutation.mutateAsync({ id: item.id, payload: { reference: reference.trim() || undefined } });
      toast({ title: 'Release order issued' });
      onClose();
    } catch (error) {
      toast({ variant: 'destructive', title: 'Release failed', description: extractErrorMessage(error) });
    }
  };

  return (
    <Modal opened={opened} onClose={onClose} title="Issue release order (DO)" centered size="md">
      <Stack gap="md">
        <Alert icon={<Info size={16} />} color="orange" variant="light">
          <Text size="sm">
            Records the delivery order / release order sent to the customer. Once issued, the goods can be
            picked up and delivered.
          </Text>
        </Alert>
        <TextInput
          label="Release order reference"
          placeholder="e.g. DO-2026-001"
          value={reference}
          onChange={(e) => setReference(e.currentTarget.value)}
        />
        <Group justify="flex-end" mt="sm">
          <Button variant="default" onClick={onClose} disabled={releaseMutation.isPending}>
            Cancel
          </Button>
          <Button color="orange" onClick={handleSubmit} loading={releaseMutation.isPending}>
            Issue release order
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
}
