import { useEffect, useState } from 'react';
import { Button, Group, Modal, NumberInput, Select, Stack, TextInput } from '@mantine/core';

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

import { api } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import type { SaveYardPayload, WarehouseYard, WarehouseYardType } from '@/types/warehouse';
import { extractErrorMessage, statusOptions, yardTypeOptions } from './options';

interface CreateYardModalProps {
  opened: boolean;
  onClose: () => void;
  warehouseId: string;
  yard?: WarehouseYard | null;
}

interface FormState {
  name: string;
  code: string;
  type: WarehouseYardType;
  capacityWeight: number | '';
  capacityContainers: number | '';
  maxVolume: number | '';
  status: 'ACTIVE' | 'INACTIVE';
}

const emptyForm = (): FormState => ({
  name: '',
  code: '',
  type: 'CONTAINER_YARD',
  capacityWeight: '',
  capacityContainers: '',
  maxVolume: '',
  status: 'ACTIVE',
});

export function CreateYardModal({ opened, onClose, warehouseId, yard }: CreateYardModalProps) {
  const isEdit = Boolean(yard);
  const { toast } = useToast();
  const createMutation = useMutation(api.warehouses.createYard.mutationOptions());
  const updateMutation = useMutation(api.warehouses.updateYard.mutationOptions());
  const [form, setForm] = useState<FormState>(emptyForm());

  useEffect(() => {
    if (opened) {
      setForm(
        yard
          ? {
              name: yard.name,
              code: yard.code,
              type: yard.type,
              capacityWeight: yard.capacityWeight ?? '',
              capacityContainers: yard.capacityContainers ?? '',
              maxVolume: yard.maxVolume ?? '',
              status: yard.status,
            }
          : emptyForm(),
      );
    }
  }, [opened, yard]);

  const submitting = createMutation.isPending || updateMutation.isPending;

  const handleSubmit = async () => {
    if (!form.name.trim() || !form.code.trim()) {
      toast({ variant: 'destructive', title: 'Name and code are required' });
      return;
    }

    const payload: SaveYardPayload = {
      name: form.name.trim(),
      code: form.code.trim(),
      type: form.type,
      capacityWeight: form.capacityWeight === '' ? undefined : Number(form.capacityWeight),
      capacityContainers: form.capacityContainers === '' ? undefined : Number(form.capacityContainers),
      maxVolume: form.maxVolume === '' ? undefined : Number(form.maxVolume),
    };

    try {
      if (yard) {
        await updateMutation.mutateAsync({ id: yard.id, payload: { ...payload, status: form.status } });
        toast({ title: 'Yard updated' });
      } else {
        await createMutation.mutateAsync({ warehouseId, payload });
        toast({ title: 'Yard created' });
      }
      onClose();
    } catch (error) {
      toast({ variant: 'destructive', title: 'Save failed', description: extractErrorMessage(error) });
    }
  };

  return (
    <Modal opened={opened} onClose={onClose} title={isEdit ? 'Edit yard' : 'Create yard'} centered size="lg">
      <Stack gap="md">
        <Group grow>
          <TextInput
            label="Name"
            placeholder="Container Yard A"
            required
            value={form.name}
            onChange={(e) => { const v = e.currentTarget.value; setForm((f) => ({ ...f, name: v })); }}
          />
          <TextInput
            label="Code"
            placeholder="CY-A"
            required
            value={form.code}
            onChange={(e) => { const v = e.currentTarget.value; setForm((f) => ({ ...f, code: v })); }}
          />
        </Group>

        <Group grow>
          <Select
            label="Type"
            data={yardTypeOptions}
            value={form.type}
            onChange={(value) => setForm((f) => ({ ...f, type: (value as WarehouseYardType) ?? 'CONTAINER_YARD' }))}
            allowDeselect={false}
          />
          {isEdit && (
            <Select
              label="Status"
              data={statusOptions}
              value={form.status}
              onChange={(value) => setForm((f) => ({ ...f, status: (value as 'ACTIVE' | 'INACTIVE') ?? 'ACTIVE' }))}
              allowDeselect={false}
            />
          )}
        </Group>

        <Group grow>
          <NumberInput
            label="Capacity weight (kg)"
            placeholder="Optional"
            min={0}
            value={form.capacityWeight}
            onChange={(value) => setForm((f) => ({ ...f, capacityWeight: value === '' ? '' : Number(value) }))}
          />
          <NumberInput
            label="Capacity containers"
            placeholder="Optional"
            min={0}
            value={form.capacityContainers}
            onChange={(value) => setForm((f) => ({ ...f, capacityContainers: value === '' ? '' : Number(value) }))}
          />
          <NumberInput
            label="Max volume (m³)"
            placeholder="Optional"
            min={0}
            value={form.maxVolume}
            onChange={(value) => setForm((f) => ({ ...f, maxVolume: value === '' ? '' : Number(value) }))}
          />
        </Group>

        <Group justify="flex-end" mt="sm">
          <Button variant="default" onClick={onClose} disabled={submitting}>
            Cancel
          </Button>
          <Button onClick={handleSubmit} loading={submitting}>
            {isEdit ? 'Save changes' : 'Create yard'}
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
}
