import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Card,
  Button,
  Modal,
  Stack,
  Group,
  Select,
  TextInput,
  Textarea,
  NumberInput,
  Table,
  Badge,
  Text,
  Title,
  Container,
  Tabs,
  Loader,
  Switch,
  ActionIcon,
} from '@mantine/core';
import { Plus, Trash2, Pencil, Wrench, Package, ShieldCheck } from 'lucide-react';
import Breadcrumbs from '@/components/ui/Breadcrumbs';
import { useToast } from '@/hooks/use-toast';
import {
  maintenanceDepthService,
  type WorkOrder,
  type WorkOrderStatus,
  type WorkOrderPriority,
  type Part,
  type Warranty,
} from '@/services/maintenance-depth.service';
import { vehiclesService, type Vehicle as VehicleType } from '@/services/vehicles.service';

const WORK_ORDER_STATUSES: WorkOrderStatus[] = ['OPEN', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED'];
const WORK_ORDER_PRIORITIES: WorkOrderPriority[] = ['LOW', 'MEDIUM', 'HIGH', 'URGENT'];
const PART_CATEGORIES = ['TIRE', 'ENGINE', 'BRAKE', 'ELECTRICAL', 'FILTER', 'FLUID', 'OTHER'];

const etb = (x: number | string | null | undefined) =>
  `ETB ${(Number(x) || 0).toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;

const statusColor = (status: string) => {
  const colors: Record<string, string> = {
    OPEN: 'edr-blue',
    IN_PROGRESS: 'edr-amber-soft',
    COMPLETED: 'edr-green',
    CANCELLED: 'edr-slate',
  };
  return colors[status] || 'edr-slate';
};

const priorityColor = (priority: string) => {
  const colors: Record<string, string> = {
    LOW: 'edr-slate',
    MEDIUM: 'edr-blue',
    HIGH: 'edr-amber-soft',
    URGENT: 'edr-red',
  };
  return colors[priority] || 'edr-slate';
};

const emptyWorkOrder = {
  vehicleId: '',
  title: '',
  description: '',
  status: 'OPEN' as WorkOrderStatus,
  priority: 'MEDIUM' as WorkOrderPriority,
  assignedTo: '',
  laborCost: 0,
  partsCost: 0,
};

const emptyPart = {
  name: '',
  sku: '',
  category: 'TIRE',
  quantityInStock: 0,
  reorderLevel: 0,
  unitCost: 0,
  location: '',
};

const emptyWarranty = {
  vehicleId: '',
  component: '',
  provider: '',
  startDate: '',
  expiryDate: new Date().toISOString().split('T')[0],
  coverageNotes: '',
};

export default function WorkOrdersPage() {
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const [activeTab, setActiveTab] = useState<string | null>('work-orders');

  // Work orders
  const [statusFilter, setStatusFilter] = useState<string | null>(null);
  const [openWorkOrderModal, setOpenWorkOrderModal] = useState(false);
  const [workOrderForm, setWorkOrderForm] = useState(emptyWorkOrder);

  // Parts
  const [lowStockOnly, setLowStockOnly] = useState(false);
  const [openPartModal, setOpenPartModal] = useState(false);
  const [editingPartId, setEditingPartId] = useState<string | null>(null);
  const [partForm, setPartForm] = useState(emptyPart);

  // Warranties
  const [openWarrantyModal, setOpenWarrantyModal] = useState(false);
  const [warrantyForm, setWarrantyForm] = useState(emptyWarranty);

  const { data: vehiclesData } = useQuery({
    queryKey: ['vehicles', 'all-for-maintenance-depth'],
    queryFn: async () => {
      const res = await vehiclesService.getAll({ limit: 1000 });
      return res.data || [];
    },
  });

  const vehicleOptions =
    vehiclesData?.map((v: VehicleType) => ({
      value: v.id,
      label: v.plateNumber
        ? `${v.plateNumber} - ${v.manufacturer} ${v.model}`
        : v.registrationNumber || v.id,
    })) || [];

  const vehicleLabel = (vehicleId: string) =>
    vehicleOptions.find((o) => o.value === vehicleId)?.label || vehicleId;

  // ---- Work orders queries/mutations ----
  const { data: workOrders, isLoading: workOrdersLoading } = useQuery({
    queryKey: ['maintenance-work-orders', statusFilter],
    queryFn: async () => {
      const res = await maintenanceDepthService.getWorkOrders({
        status: (statusFilter as WorkOrderStatus) || undefined,
      });
      return res.data || [];
    },
  });
  const workOrderList: WorkOrder[] = Array.isArray(workOrders) ? workOrders : [];

  const createWorkOrderMutation = useMutation({
    mutationFn: async () => {
      const res = await maintenanceDepthService.createWorkOrder({
        vehicleId: workOrderForm.vehicleId,
        title: workOrderForm.title,
        description: workOrderForm.description || undefined,
        status: workOrderForm.status,
        priority: workOrderForm.priority,
        assignedTo: workOrderForm.assignedTo || undefined,
        laborCost: Number(workOrderForm.laborCost) || undefined,
        partsCost: Number(workOrderForm.partsCost) || undefined,
      });
      return res.data;
    },
    onSuccess: () => {
      toast({ title: 'Work order created' });
      queryClient.invalidateQueries({ queryKey: ['maintenance-work-orders'] });
      setOpenWorkOrderModal(false);
      setWorkOrderForm(emptyWorkOrder);
    },
    onError: (err: any) => {
      toast({
        title: 'Error',
        description: err?.response?.data?.message ?? 'Failed',
        variant: 'destructive',
      });
    },
  });

  const deleteWorkOrderMutation = useMutation({
    mutationFn: async (id: string) => {
      await maintenanceDepthService.deleteWorkOrder(id);
    },
    onSuccess: () => {
      toast({ title: 'Work order deleted' });
      queryClient.invalidateQueries({ queryKey: ['maintenance-work-orders'] });
    },
    onError: (err: any) => {
      toast({
        title: 'Error',
        description: err?.response?.data?.message ?? 'Failed',
        variant: 'destructive',
      });
    },
  });

  // ---- Parts queries/mutations ----
  const { data: parts, isLoading: partsLoading } = useQuery({
    queryKey: ['maintenance-parts', lowStockOnly],
    queryFn: async () => {
      const res = await maintenanceDepthService.getParts({ lowStock: lowStockOnly || undefined });
      return res.data || [];
    },
  });
  const partList: Part[] = Array.isArray(parts) ? parts : [];

  const savePartMutation = useMutation({
    mutationFn: async () => {
      const payload = {
        name: partForm.name,
        sku: partForm.sku || undefined,
        category: partForm.category || undefined,
        quantityInStock: Number(partForm.quantityInStock) || 0,
        reorderLevel: Number(partForm.reorderLevel) || 0,
        unitCost: Number(partForm.unitCost) || undefined,
        location: partForm.location || undefined,
      };
      if (editingPartId) {
        const res = await maintenanceDepthService.updatePart(editingPartId, payload);
        return res.data;
      }
      const res = await maintenanceDepthService.createPart(payload);
      return res.data;
    },
    onSuccess: () => {
      toast({ title: editingPartId ? 'Part updated' : 'Part created' });
      queryClient.invalidateQueries({ queryKey: ['maintenance-parts'] });
      setOpenPartModal(false);
      setPartForm(emptyPart);
      setEditingPartId(null);
    },
    onError: (err: any) => {
      toast({
        title: 'Error',
        description: err?.response?.data?.message ?? 'Failed',
        variant: 'destructive',
      });
    },
  });

  const deletePartMutation = useMutation({
    mutationFn: async (id: string) => {
      await maintenanceDepthService.deletePart(id);
    },
    onSuccess: () => {
      toast({ title: 'Part deleted' });
      queryClient.invalidateQueries({ queryKey: ['maintenance-parts'] });
    },
    onError: (err: any) => {
      toast({
        title: 'Error',
        description: err?.response?.data?.message ?? 'Failed',
        variant: 'destructive',
      });
    },
  });

  // ---- Warranties queries/mutations ----
  const { data: warranties, isLoading: warrantiesLoading } = useQuery({
    queryKey: ['maintenance-warranties'],
    queryFn: async () => {
      const res = await maintenanceDepthService.getWarranties();
      return res.data || [];
    },
  });
  const warrantyList: Warranty[] = Array.isArray(warranties) ? warranties : [];

  const createWarrantyMutation = useMutation({
    mutationFn: async () => {
      const res = await maintenanceDepthService.createWarranty({
        vehicleId: warrantyForm.vehicleId,
        component: warrantyForm.component,
        provider: warrantyForm.provider || undefined,
        startDate: warrantyForm.startDate || undefined,
        expiryDate: warrantyForm.expiryDate,
        coverageNotes: warrantyForm.coverageNotes || undefined,
      });
      return res.data;
    },
    onSuccess: () => {
      toast({ title: 'Warranty created' });
      queryClient.invalidateQueries({ queryKey: ['maintenance-warranties'] });
      setOpenWarrantyModal(false);
      setWarrantyForm(emptyWarranty);
    },
    onError: (err: any) => {
      toast({
        title: 'Error',
        description: err?.response?.data?.message ?? 'Failed',
        variant: 'destructive',
      });
    },
  });

  const deleteWarrantyMutation = useMutation({
    mutationFn: async (id: string) => {
      await maintenanceDepthService.deleteWarranty(id);
    },
    onSuccess: () => {
      toast({ title: 'Warranty deleted' });
      queryClient.invalidateQueries({ queryKey: ['maintenance-warranties'] });
    },
    onError: (err: any) => {
      toast({
        title: 'Error',
        description: err?.response?.data?.message ?? 'Failed',
        variant: 'destructive',
      });
    },
  });

  const openPartForEdit = (part: Part) => {
    setEditingPartId(part.id);
    setPartForm({
      name: part.name,
      sku: part.sku || '',
      category: part.category || 'OTHER',
      quantityInStock: part.quantityInStock,
      reorderLevel: part.reorderLevel,
      unitCost: Number(part.unitCost) || 0,
      location: part.location || '',
    });
    setOpenPartModal(true);
  };

  const openPartForCreate = () => {
    setEditingPartId(null);
    setPartForm(emptyPart);
    setOpenPartModal(true);
  };

  return (
    <Container size="xl" py="xl" px="lg">
      <Breadcrumbs items={[{ label: 'Fleet' }, { label: 'Maintenance' }, { label: 'Work Orders' }]} />

      <Group justify="space-between" mb="lg">
        <Title order={1}>Work Orders &amp; Parts</Title>
      </Group>

      <Tabs value={activeTab} onChange={setActiveTab}>
        <Tabs.List>
          <Tabs.Tab value="work-orders" leftSection={<Wrench size={14} />}>
            Work Orders
          </Tabs.Tab>
          <Tabs.Tab value="parts" leftSection={<Package size={14} />}>
            Parts / Tires
          </Tabs.Tab>
          <Tabs.Tab value="warranties" leftSection={<ShieldCheck size={14} />}>
            Warranties
          </Tabs.Tab>
        </Tabs.List>

        {/* ---- Work Orders tab ---- */}
        <Tabs.Panel value="work-orders" pt="lg">
          <Group justify="space-between" mb="md">
            <Select
              placeholder="All statuses"
              data={WORK_ORDER_STATUSES}
              value={statusFilter}
              onChange={setStatusFilter}
              clearable
              w={220}
            />
            <Button
              onClick={() => setOpenWorkOrderModal(true)}
              color="edr-green"
              leftSection={<Plus size={16} />}
            >
              New Work Order
            </Button>
          </Group>

          <Card withBorder>
            {workOrdersLoading ? (
              <Group justify="center" p="xl">
                <Loader />
              </Group>
            ) : workOrderList.length > 0 ? (
              <Table.ScrollContainer minWidth={800}>
                <Table striped highlightOnHover>
                  <Table.Thead>
                    <Table.Tr>
                      <Table.Th>Title</Table.Th>
                      <Table.Th>Vehicle</Table.Th>
                      <Table.Th>Priority</Table.Th>
                      <Table.Th>Status</Table.Th>
                      <Table.Th>Assigned</Table.Th>
                      <Table.Th>Labor</Table.Th>
                      <Table.Th>Parts</Table.Th>
                      <Table.Th>Opened</Table.Th>
                      <Table.Th />
                    </Table.Tr>
                  </Table.Thead>
                  <Table.Tbody>
                    {workOrderList.map((wo) => (
                      <Table.Tr key={wo.id}>
                        <Table.Td>{wo.title}</Table.Td>
                        <Table.Td>{vehicleLabel(wo.vehicleId)}</Table.Td>
                        <Table.Td>
                          <Badge color={priorityColor(wo.priority)}>{wo.priority}</Badge>
                        </Table.Td>
                        <Table.Td>
                          <Badge color={statusColor(wo.status)}>{wo.status}</Badge>
                        </Table.Td>
                        <Table.Td>{wo.assignedTo || '—'}</Table.Td>
                        <Table.Td>{etb(wo.laborCost)}</Table.Td>
                        <Table.Td>{etb(wo.partsCost)}</Table.Td>
                        <Table.Td>{new Date(wo.openedAt).toLocaleDateString()}</Table.Td>
                        <Table.Td>
                          <ActionIcon
                            variant="subtle"
                            color="edr-red"
                            onClick={() => deleteWorkOrderMutation.mutate(wo.id)}
                            aria-label="Delete work order"
                          >
                            <Trash2 size={16} />
                          </ActionIcon>
                        </Table.Td>
                      </Table.Tr>
                    ))}
                  </Table.Tbody>
                </Table>
              </Table.ScrollContainer>
            ) : (
              <Text c="dimmed" ta="center" p="xl">
                No work orders yet
              </Text>
            )}
          </Card>
        </Tabs.Panel>

        {/* ---- Parts / Tires tab ---- */}
        <Tabs.Panel value="parts" pt="lg">
          <Group justify="space-between" mb="md">
            <Switch
              label="Low stock only"
              checked={lowStockOnly}
              onChange={(e) => setLowStockOnly(e.currentTarget.checked)}
            />
            <Button onClick={openPartForCreate} color="edr-green" leftSection={<Plus size={16} />}>
              New Part
            </Button>
          </Group>

          <Card withBorder>
            {partsLoading ? (
              <Group justify="center" p="xl">
                <Loader />
              </Group>
            ) : partList.length > 0 ? (
              <Table.ScrollContainer minWidth={800}>
                <Table striped highlightOnHover>
                  <Table.Thead>
                    <Table.Tr>
                      <Table.Th>Name</Table.Th>
                      <Table.Th>SKU</Table.Th>
                      <Table.Th>Category</Table.Th>
                      <Table.Th>In Stock</Table.Th>
                      <Table.Th>Reorder Level</Table.Th>
                      <Table.Th>Unit Cost</Table.Th>
                      <Table.Th>Location</Table.Th>
                      <Table.Th />
                    </Table.Tr>
                  </Table.Thead>
                  <Table.Tbody>
                    {partList.map((p) => (
                      <Table.Tr key={p.id}>
                        <Table.Td>{p.name}</Table.Td>
                        <Table.Td>{p.sku || '—'}</Table.Td>
                        <Table.Td>
                          {p.category ? <Badge variant="light">{p.category}</Badge> : '—'}
                        </Table.Td>
                        <Table.Td>
                          <Group gap="xs">
                            {p.quantityInStock}
                            {p.quantityInStock <= p.reorderLevel && (
                              <Badge color="edr-red" size="sm">
                                Low stock
                              </Badge>
                            )}
                          </Group>
                        </Table.Td>
                        <Table.Td>{p.reorderLevel}</Table.Td>
                        <Table.Td>{etb(p.unitCost)}</Table.Td>
                        <Table.Td>{p.location || '—'}</Table.Td>
                        <Table.Td>
                          <Group gap={4} wrap="nowrap">
                            <ActionIcon
                              variant="subtle"
                              onClick={() => openPartForEdit(p)}
                              aria-label="Adjust part"
                            >
                              <Pencil size={16} />
                            </ActionIcon>
                            <ActionIcon
                              variant="subtle"
                              color="edr-red"
                              onClick={() => deletePartMutation.mutate(p.id)}
                              aria-label="Delete part"
                            >
                              <Trash2 size={16} />
                            </ActionIcon>
                          </Group>
                        </Table.Td>
                      </Table.Tr>
                    ))}
                  </Table.Tbody>
                </Table>
              </Table.ScrollContainer>
            ) : (
              <Text c="dimmed" ta="center" p="xl">
                No parts in inventory
              </Text>
            )}
          </Card>
        </Tabs.Panel>

        {/* ---- Warranties tab ---- */}
        <Tabs.Panel value="warranties" pt="lg">
          <Group justify="flex-end" mb="md">
            <Button
              onClick={() => setOpenWarrantyModal(true)}
              color="edr-green"
              leftSection={<Plus size={16} />}
            >
              New Warranty
            </Button>
          </Group>

          <Card withBorder>
            {warrantiesLoading ? (
              <Group justify="center" p="xl">
                <Loader />
              </Group>
            ) : warrantyList.length > 0 ? (
              <Table.ScrollContainer minWidth={700}>
                <Table striped highlightOnHover>
                  <Table.Thead>
                    <Table.Tr>
                      <Table.Th>Component</Table.Th>
                      <Table.Th>Vehicle</Table.Th>
                      <Table.Th>Provider</Table.Th>
                      <Table.Th>Start</Table.Th>
                      <Table.Th>Expiry</Table.Th>
                      <Table.Th />
                    </Table.Tr>
                  </Table.Thead>
                  <Table.Tbody>
                    {warrantyList.map((w) => {
                      const expired = new Date(w.expiryDate) < new Date();
                      return (
                        <Table.Tr key={w.id}>
                          <Table.Td>{w.component}</Table.Td>
                          <Table.Td>{vehicleLabel(w.vehicleId)}</Table.Td>
                          <Table.Td>{w.provider || '—'}</Table.Td>
                          <Table.Td>
                            {w.startDate ? new Date(w.startDate).toLocaleDateString() : '—'}
                          </Table.Td>
                          <Table.Td>
                            <Group gap="xs">
                              {new Date(w.expiryDate).toLocaleDateString()}
                              <Badge color={expired ? 'edr-red' : 'edr-green'} size="sm">
                                {expired ? 'Expired' : 'Active'}
                              </Badge>
                            </Group>
                          </Table.Td>
                          <Table.Td>
                            <ActionIcon
                              variant="subtle"
                              color="edr-red"
                              onClick={() => deleteWarrantyMutation.mutate(w.id)}
                              aria-label="Delete warranty"
                            >
                              <Trash2 size={16} />
                            </ActionIcon>
                          </Table.Td>
                        </Table.Tr>
                      );
                    })}
                  </Table.Tbody>
                </Table>
              </Table.ScrollContainer>
            ) : (
              <Text c="dimmed" ta="center" p="xl">
                No warranties recorded
              </Text>
            )}
          </Card>
        </Tabs.Panel>
      </Tabs>

      {/* ---- Work Order modal ---- */}
      <Modal
        opened={openWorkOrderModal}
        onClose={() => setOpenWorkOrderModal(false)}
        title="New Work Order"
        size="md"
      >
        <Stack gap="md">
          <Select
            label="Vehicle"
            placeholder="Pick a vehicle"
            data={vehicleOptions}
            value={workOrderForm.vehicleId || null}
            onChange={(v) => setWorkOrderForm({ ...workOrderForm, vehicleId: v || '' })}
            searchable
            required
          />
          <TextInput
            label="Title"
            placeholder="e.g., Replace front brake pads"
            value={workOrderForm.title}
            onChange={(e) => setWorkOrderForm({ ...workOrderForm, title: e.currentTarget.value })}
            required
          />
          <Textarea
            label="Description"
            placeholder="Details of the work needed"
            value={workOrderForm.description}
            onChange={(e) =>
              setWorkOrderForm({ ...workOrderForm, description: e.currentTarget.value })
            }
          />
          <Group grow>
            <Select
              label="Priority"
              data={WORK_ORDER_PRIORITIES}
              value={workOrderForm.priority}
              onChange={(v) =>
                setWorkOrderForm({ ...workOrderForm, priority: (v as WorkOrderPriority) || 'MEDIUM' })
              }
            />
            <Select
              label="Status"
              data={WORK_ORDER_STATUSES}
              value={workOrderForm.status}
              onChange={(v) =>
                setWorkOrderForm({ ...workOrderForm, status: (v as WorkOrderStatus) || 'OPEN' })
              }
            />
          </Group>
          <TextInput
            label="Assigned To"
            placeholder="e.g., Mechanic name"
            value={workOrderForm.assignedTo}
            onChange={(e) =>
              setWorkOrderForm({ ...workOrderForm, assignedTo: e.currentTarget.value })
            }
          />
          <Group grow>
            <NumberInput
              label="Labor Cost (ETB)"
              min={0}
              value={workOrderForm.laborCost}
              onChange={(v) => setWorkOrderForm({ ...workOrderForm, laborCost: Number(v) || 0 })}
            />
            <NumberInput
              label="Parts Cost (ETB)"
              min={0}
              value={workOrderForm.partsCost}
              onChange={(v) => setWorkOrderForm({ ...workOrderForm, partsCost: Number(v) || 0 })}
            />
          </Group>
          <Group justify="flex-end">
            <Button variant="light" onClick={() => setOpenWorkOrderModal(false)}>
              Cancel
            </Button>
            <Button
              onClick={() => createWorkOrderMutation.mutate()}
              loading={createWorkOrderMutation.isPending}
              disabled={!workOrderForm.vehicleId || !workOrderForm.title}
            >
              Create
            </Button>
          </Group>
        </Stack>
      </Modal>

      {/* ---- Part modal ---- */}
      <Modal
        opened={openPartModal}
        onClose={() => {
          setOpenPartModal(false);
          setEditingPartId(null);
        }}
        title={editingPartId ? 'Adjust Part' : 'New Part'}
        size="md"
      >
        <Stack gap="md">
          <TextInput
            label="Name"
            placeholder="e.g., 315/80R22.5 Tire"
            value={partForm.name}
            onChange={(e) => setPartForm({ ...partForm, name: e.currentTarget.value })}
            required
          />
          <Group grow>
            <TextInput
              label="SKU"
              placeholder="Optional"
              value={partForm.sku}
              onChange={(e) => setPartForm({ ...partForm, sku: e.currentTarget.value })}
            />
            <Select
              label="Category"
              data={PART_CATEGORIES}
              value={partForm.category}
              onChange={(v) => setPartForm({ ...partForm, category: v || 'OTHER' })}
            />
          </Group>
          <Group grow>
            <NumberInput
              label="Quantity in Stock"
              min={0}
              value={partForm.quantityInStock}
              onChange={(v) => setPartForm({ ...partForm, quantityInStock: Number(v) || 0 })}
            />
            <NumberInput
              label="Reorder Level"
              min={0}
              value={partForm.reorderLevel}
              onChange={(v) => setPartForm({ ...partForm, reorderLevel: Number(v) || 0 })}
            />
          </Group>
          <Group grow>
            <NumberInput
              label="Unit Cost (ETB)"
              min={0}
              value={partForm.unitCost}
              onChange={(v) => setPartForm({ ...partForm, unitCost: Number(v) || 0 })}
            />
            <TextInput
              label="Location"
              placeholder="e.g., Shelf A3"
              value={partForm.location}
              onChange={(e) => setPartForm({ ...partForm, location: e.currentTarget.value })}
            />
          </Group>
          <Group justify="flex-end">
            <Button
              variant="light"
              onClick={() => {
                setOpenPartModal(false);
                setEditingPartId(null);
              }}
            >
              Cancel
            </Button>
            <Button
              onClick={() => savePartMutation.mutate()}
              loading={savePartMutation.isPending}
              disabled={!partForm.name}
            >
              {editingPartId ? 'Save' : 'Create'}
            </Button>
          </Group>
        </Stack>
      </Modal>

      {/* ---- Warranty modal ---- */}
      <Modal
        opened={openWarrantyModal}
        onClose={() => setOpenWarrantyModal(false)}
        title="New Warranty"
        size="md"
      >
        <Stack gap="md">
          <Select
            label="Vehicle"
            placeholder="Pick a vehicle"
            data={vehicleOptions}
            value={warrantyForm.vehicleId || null}
            onChange={(v) => setWarrantyForm({ ...warrantyForm, vehicleId: v || '' })}
            searchable
            required
          />
          <TextInput
            label="Component"
            placeholder="e.g., Engine, Transmission"
            value={warrantyForm.component}
            onChange={(e) => setWarrantyForm({ ...warrantyForm, component: e.currentTarget.value })}
            required
          />
          <TextInput
            label="Provider"
            placeholder="e.g., Manufacturer name"
            value={warrantyForm.provider}
            onChange={(e) => setWarrantyForm({ ...warrantyForm, provider: e.currentTarget.value })}
          />
          <Group grow>
            <TextInput
              label="Start Date"
              type="date"
              value={warrantyForm.startDate}
              onChange={(e) =>
                setWarrantyForm({ ...warrantyForm, startDate: e.currentTarget.value })
              }
            />
            <TextInput
              label="Expiry Date"
              type="date"
              value={warrantyForm.expiryDate}
              onChange={(e) =>
                setWarrantyForm({ ...warrantyForm, expiryDate: e.currentTarget.value })
              }
              required
            />
          </Group>
          <Textarea
            label="Coverage Notes"
            placeholder="What the warranty covers"
            value={warrantyForm.coverageNotes}
            onChange={(e) =>
              setWarrantyForm({ ...warrantyForm, coverageNotes: e.currentTarget.value })
            }
          />
          <Group justify="flex-end">
            <Button variant="light" onClick={() => setOpenWarrantyModal(false)}>
              Cancel
            </Button>
            <Button
              onClick={() => createWarrantyMutation.mutate()}
              loading={createWarrantyMutation.isPending}
              disabled={!warrantyForm.vehicleId || !warrantyForm.component || !warrantyForm.expiryDate}
            >
              Create
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Container>
  );
}
