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 { SaveZonePayload, WarehouseZone, WarehouseZoneType } from '@/types/warehouse';
import { extractErrorMessage, statusOptions, zoneTypeOptions } from './options';

interface CreateZoneModalProps {
  opened: boolean;
  onClose: () => void;
  yardId: string;
  zone?: WarehouseZone | null;
}

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

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

export function CreateZoneModal({ opened, onClose, yardId, zone }: CreateZoneModalProps) {
  const isEdit = Boolean(zone);
  const { toast } = useToast();
  const createMutation = useMutation(api.warehouses.createZone.mutationOptions());
  const updateMutation = useMutation(api.warehouses.updateZone.mutationOptions());
  const [form, setForm] = useState<FormState>(emptyForm());

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

  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: SaveZonePayload = {
      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 (zone) {
        await updateMutation.mutateAsync({ id: zone.id, payload: { ...payload, status: form.status } });
        toast({ title: 'Zone updated' });
      } else {
        await createMutation.mutateAsync({ yardId, payload });
        toast({ title: 'Zone created' });
      }
      onClose();
    } catch (error) {
      toast({ variant: 'destructive', title: 'Save failed', description: extractErrorMessage(error) });
    }
  };

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

        <Group grow>
          <Select
            label="Type"
            data={zoneTypeOptions}
            value={form.type}
            onChange={(value) => setForm((f) => ({ ...f, type: (value as WarehouseZoneType) ?? 'CONTAINER_ZONE' }))}
            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 zone'}
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
}
