import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Card,
  Button,
  Modal,
  Stack,
  Group,
  Select,
  TextInput,
  NumberInput,
  Table,
  Badge,
  Text,
  Title,
  Container,
  ActionIcon,
  Tooltip,
} from '@mantine/core';
import { CheckCircle2, Plus, Trash2 } from 'lucide-react';
import Breadcrumbs from '@/components/ui/Breadcrumbs';
import { useToast } from '@/hooks/use-toast';
import { QUERY_KEYS } from '@/constants/QUERY_KEYS';
import { api } from '@/auth/http';
import { vehiclesService, type Vehicle as VehicleType } from '@/services/vehicles.service';

interface MaintenanceSchedule {
  id: string;
  vehicleId: string;
  maintenanceType: string;
  serviceItem?: string | null;
  description: string;
  scheduledDate: string;
  completedDate?: string;
  status: string;
  estimatedCost?: number;
  actualCost?: number;
  serviceProvider?: string;
}

interface DueBoardRow {
  scheduleId: string;
  vehicleId: string;
  plateNumber: string;
  maintenanceType: string;
  serviceItem: string | null;
  description: string;
  scheduledDate: string;
  nextDueDate: string | null;
  nextDueKm: number | null;
  currentKm: number | null;
  kmRemaining: number | null;
  daysRemaining: number | null;
  overdue: boolean;
}

interface MaintenanceInterval {
  id: string;
  vehicleId: string;
  maintenanceType: string;
  serviceItem: string | null;
  intervalKm: number | null;
  intervalDays: number | null;
  description: string | null;
  isActive: boolean;
}

const emptyForm = {
  maintenanceType: 'PREVENTIVE',
  serviceItem: '',
  description: '',
  scheduledDate: new Date().toISOString().split('T')[0],
  estimatedCost: 0,
  serviceProvider: '',
  notes: '',
};

const emptyIntervalForm = {
  maintenanceType: 'PREVENTIVE',
  serviceItem: '',
  intervalKm: '' as number | '',
  intervalDays: '' as number | '',
  description: '',
};

export function MaintenancePage() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedVehicle, setSelectedVehicle] = useState<string | null>(null);
  const [openScheduleModal, setOpenScheduleModal] = useState(false);
  const [formData, setFormData] = useState(emptyForm);
  const [intervalForm, setIntervalForm] = useState(emptyIntervalForm);
  const [completeTarget, setCompleteTarget] = useState<MaintenanceSchedule | null>(null);
  const [completeOdometer, setCompleteOdometer] = useState<number | ''>('');
  const [completeCost, setCompleteCost] = useState<number | ''>('');

  // Maintenance is driven by time AND km, not a picked-then-scheduled action —
  // this is the fleet-wide board of what's actually due, by date or mileage.
  const { data: dueBoard, isLoading: dueLoading } = useQuery({
    queryKey: QUERY_KEYS.MAINTENANCE.dueBoard(),
    queryFn: async () => {
      const res = await api.get('/maintenance/due-board');
      return (res.data || []) as DueBoardRow[];
    },
  });

  const { data: vehiclesData } = useQuery({
    queryKey: QUERY_KEYS.VEHICLES.list(),
    queryFn: async () => {
      const res = await vehiclesService.getAll({ limit: 1000 });
      return res.data || [];
    },
  });

  const { data: upcoming, isLoading } = useQuery({
    queryKey: QUERY_KEYS.MAINTENANCE.upcoming(selectedVehicle || ''),
    queryFn: async () => {
      if (!selectedVehicle) return [];
      const res = await api.get(`/maintenance/upcoming/${selectedVehicle}`);
      return res.data || [];
    },
    enabled: !!selectedVehicle,
  });

  const { data: intervals } = useQuery({
    queryKey: QUERY_KEYS.MAINTENANCE.intervals(selectedVehicle || ''),
    queryFn: async () => {
      if (!selectedVehicle) return [];
      const res = await api.get(`/maintenance/intervals/${selectedVehicle}`);
      return (res.data || []) as MaintenanceInterval[];
    },
    enabled: !!selectedVehicle,
  });

  const upcomingList: MaintenanceSchedule[] = Array.isArray(upcoming) ? upcoming : [];
  const intervalList: MaintenanceInterval[] = Array.isArray(intervals) ? intervals : [];

  const invalidateVehicle = () => {
    void queryClient.invalidateQueries({ queryKey: QUERY_KEYS.MAINTENANCE.ROOT });
  };

  const onError = (err: unknown) => {
    toast({
      title: 'Error',
      description:
        (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
        'Failed',
      variant: 'destructive',
    });
  };

  const scheduleMutation = useMutation({
    mutationFn: async () => {
      if (!selectedVehicle) return;
      const res = await api.post('/maintenance/schedules', {
        vehicleId: selectedVehicle,
        ...formData,
        serviceItem: formData.serviceItem.trim() || undefined,
      });
      return res.data;
    },
    onSuccess: () => {
      toast({ title: 'Maintenance scheduled' });
      invalidateVehicle();
      setOpenScheduleModal(false);
      setFormData(emptyForm);
    },
    onError,
  });

  // Interval upsert: "oil change every 10,000 km" — drives the auto-scheduling
  // of the next service when a maintenance completes with an odometer reading.
  const intervalMutation = useMutation({
    mutationFn: async () => {
      if (!selectedVehicle) return;
      const res = await api.post('/maintenance/intervals', {
        vehicleId: selectedVehicle,
        maintenanceType: intervalForm.maintenanceType,
        serviceItem: intervalForm.serviceItem.trim() || undefined,
        intervalKm: intervalForm.intervalKm === '' ? undefined : Number(intervalForm.intervalKm),
        intervalDays:
          intervalForm.intervalDays === '' ? undefined : Number(intervalForm.intervalDays),
        description: intervalForm.description.trim() || undefined,
      });
      return res.data;
    },
    onSuccess: () => {
      toast({ title: 'Interval saved' });
      invalidateVehicle();
      setIntervalForm(emptyIntervalForm);
    },
    onError,
  });

  const deactivateIntervalMutation = useMutation({
    mutationFn: async (id: string) => api.delete(`/maintenance/intervals/${id}`),
    onSuccess: () => {
      toast({ title: 'Interval deactivated' });
      invalidateVehicle();
    },
    onError,
  });

  // Completion with odometer: the reading is what advances KM-based
  // scheduling — the API auto-creates the next SCHEDULED item from it.
  const completeMutation = useMutation({
    mutationFn: async () => {
      if (!completeTarget) return;
      const res = await api.patch(`/maintenance/schedules/${completeTarget.id}`, {
        status: 'COMPLETED',
        completedDate: new Date().toISOString(),
        odometerReading: completeOdometer === '' ? undefined : Number(completeOdometer),
        actualCost: completeCost === '' ? undefined : Number(completeCost),
      });
      return res.data;
    },
    onSuccess: () => {
      toast({
        title: 'Maintenance completed',
        description:
          completeOdometer === ''
            ? 'No odometer recorded — next service was NOT auto-scheduled.'
            : 'Next service auto-scheduled from the recorded odometer.',
      });
      invalidateVehicle();
      setCompleteTarget(null);
      setCompleteOdometer('');
      setCompleteCost('');
    },
    onError,
  });

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

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

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

      <Group justify="space-between" mb="lg">
        <Title order={1}>Maintenance</Title>
        <Button
          onClick={() => setOpenScheduleModal(true)}
          color="edr-green"
          leftSection={<Plus size={16} />}
          disabled={!selectedVehicle}
        >
          New Schedule
        </Button>
      </Group>

      <Stack gap="md">
        <Card withBorder>
          <Card.Section p="md" withBorder>
            <Text fw={500}>Due Board — by date and driven km</Text>
          </Card.Section>
          <Card.Section p="md">
            {dueLoading ? (
              <Text>Loading…</Text>
            ) : dueBoard && dueBoard.length > 0 ? (
              <Table striped highlightOnHover>
                <Table.Thead>
                  <Table.Tr>
                    <Table.Th>Vehicle</Table.Th>
                    <Table.Th>Type</Table.Th>
                    <Table.Th>Service Item</Table.Th>
                    <Table.Th>Next Due Date</Table.Th>
                    <Table.Th>Next Due Km</Table.Th>
                    <Table.Th>Current Km</Table.Th>
                    <Table.Th>Remaining</Table.Th>
                    <Table.Th>Status</Table.Th>
                  </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                  {dueBoard.map((row) => (
                    <Table.Tr
                      key={row.scheduleId}
                      onClick={() => setSelectedVehicle(row.vehicleId)}
                      style={{ cursor: 'pointer' }}
                    >
                      <Table.Td>{row.plateNumber}</Table.Td>
                      <Table.Td>{row.maintenanceType}</Table.Td>
                      <Table.Td>{row.serviceItem ?? '—'}</Table.Td>
                      <Table.Td>
                        {row.nextDueDate ? new Date(row.nextDueDate).toLocaleDateString() : '—'}
                      </Table.Td>
                      <Table.Td>{row.nextDueKm ?? '—'}</Table.Td>
                      <Table.Td>{row.currentKm ?? '—'}</Table.Td>
                      <Table.Td>
                        {row.kmRemaining != null
                          ? `${row.kmRemaining} km`
                          : row.daysRemaining != null
                            ? `${row.daysRemaining} d`
                            : '—'}
                      </Table.Td>
                      <Table.Td>
                        <Badge color={row.overdue ? 'edr-red' : 'edr-blue'}>
                          {row.overdue ? 'OVERDUE' : 'SCHEDULED'}
                        </Badge>
                      </Table.Td>
                    </Table.Tr>
                  ))}
                </Table.Tbody>
              </Table>
            ) : (
              <Text c="dimmed">Nothing scheduled fleet-wide</Text>
            )}
          </Card.Section>
        </Card>

        <Card withBorder padding="md">
          <Select
            label="Select Vehicle"
            placeholder="Pick a vehicle"
            data={vehicleOptions}
            value={selectedVehicle}
            onChange={setSelectedVehicle}
            searchable
          />
        </Card>

        {!selectedVehicle ? (
          <Card withBorder padding="lg">
            <Text c="dimmed" ta="center">
              Select a vehicle to view its maintenance schedule
            </Text>
          </Card>
        ) : (
          <>
            <Card withBorder>
              <Card.Section p="md" withBorder>
                <Text fw={500}>Service Intervals — drives auto-scheduling</Text>
                <Text size="xs" c="dimmed">
                  e.g. oil change every 10,000 km. On completion with an odometer reading, the
                  next service is scheduled automatically at reading + interval.
                </Text>
              </Card.Section>
              <Card.Section p="md">
                <Stack gap="sm">
                  {intervalList.length > 0 && (
                    <Table striped>
                      <Table.Thead>
                        <Table.Tr>
                          <Table.Th>Type</Table.Th>
                          <Table.Th>Service Item</Table.Th>
                          <Table.Th>Every (km)</Table.Th>
                          <Table.Th>Every (days)</Table.Th>
                          <Table.Th>Description</Table.Th>
                          <Table.Th />
                        </Table.Tr>
                      </Table.Thead>
                      <Table.Tbody>
                        {intervalList.map((i) => (
                          <Table.Tr key={i.id}>
                            <Table.Td>{i.maintenanceType}</Table.Td>
                            <Table.Td>{i.serviceItem ?? '—'}</Table.Td>
                            <Table.Td>{i.intervalKm ?? '—'}</Table.Td>
                            <Table.Td>{i.intervalDays ?? '—'}</Table.Td>
                            <Table.Td>{i.description ?? '—'}</Table.Td>
                            <Table.Td>
                              <Tooltip label="Deactivate — stops auto-scheduling">
                                <ActionIcon
                                  variant="subtle"
                                  color="red"
                                  onClick={() => deactivateIntervalMutation.mutate(i.id)}
                                >
                                  <Trash2 size={15} />
                                </ActionIcon>
                              </Tooltip>
                            </Table.Td>
                          </Table.Tr>
                        ))}
                      </Table.Tbody>
                    </Table>
                  )}
                  <Group align="flex-end" gap="sm" wrap="wrap">
                    <Select
                      label="Type"
                      w={150}
                      data={['PREVENTIVE', 'CORRECTIVE', 'INSPECTION', 'REPAIR']}
                      value={intervalForm.maintenanceType}
                      onChange={(v) =>
                        setIntervalForm({ ...intervalForm, maintenanceType: v || 'PREVENTIVE' })
                      }
                    />
                    <TextInput
                      label="Service item"
                      placeholder="e.g. oil change"
                      w={170}
                      value={intervalForm.serviceItem}
                      onChange={(e) =>
                        setIntervalForm({ ...intervalForm, serviceItem: e.currentTarget.value })
                      }
                    />
                    <NumberInput
                      label="Every (km)"
                      min={0}
                      w={130}
                      value={intervalForm.intervalKm}
                      onChange={(v) =>
                        setIntervalForm({ ...intervalForm, intervalKm: v === '' ? '' : Number(v) })
                      }
                    />
                    <NumberInput
                      label="Every (days)"
                      min={0}
                      w={130}
                      value={intervalForm.intervalDays}
                      onChange={(v) =>
                        setIntervalForm({
                          ...intervalForm,
                          intervalDays: v === '' ? '' : Number(v),
                        })
                      }
                    />
                    <TextInput
                      label="Description"
                      placeholder="Oil and filter change"
                      style={{ flex: 1, minWidth: 160 }}
                      value={intervalForm.description}
                      onChange={(e) =>
                        setIntervalForm({ ...intervalForm, description: e.currentTarget.value })
                      }
                    />
                    <Button
                      color="edr-green"
                      leftSection={<Plus size={14} />}
                      loading={intervalMutation.isPending}
                      disabled={
                        intervalForm.intervalKm === '' && intervalForm.intervalDays === ''
                      }
                      onClick={() => intervalMutation.mutate()}
                    >
                      Save interval
                    </Button>
                  </Group>
                </Stack>
              </Card.Section>
            </Card>

            <Card withBorder>
              <Card.Section p="md" withBorder>
                <Text fw={500}>Upcoming Maintenance</Text>
              </Card.Section>
              <Card.Section p="md">
                {isLoading ? (
                  <Text>Loading...</Text>
                ) : upcomingList.length > 0 ? (
                  <Table striped highlightOnHover>
                    <Table.Thead>
                      <Table.Tr>
                        <Table.Th>Type</Table.Th>
                        <Table.Th>Service Item</Table.Th>
                        <Table.Th>Description</Table.Th>
                        <Table.Th>Scheduled</Table.Th>
                        <Table.Th>Est. Cost</Table.Th>
                        <Table.Th>Status</Table.Th>
                        <Table.Th />
                      </Table.Tr>
                    </Table.Thead>
                    <Table.Tbody>
                      {upcomingList.map((m) => (
                        <Table.Tr key={m.id}>
                          <Table.Td>{m.maintenanceType}</Table.Td>
                          <Table.Td>{m.serviceItem ?? '—'}</Table.Td>
                          <Table.Td>{m.description}</Table.Td>
                          <Table.Td>{new Date(m.scheduledDate).toLocaleDateString()}</Table.Td>
                          <Table.Td>
                            {m.estimatedCost != null
                              ? `ETB ${Number(m.estimatedCost).toLocaleString('en-US', {
                                  minimumFractionDigits: 2,
                                  maximumFractionDigits: 2,
                                })}`
                              : '—'}
                          </Table.Td>
                          <Table.Td>
                            <Badge color={statusColor(m.status)}>{m.status}</Badge>
                          </Table.Td>
                          <Table.Td>
                            {(m.status === 'SCHEDULED' || m.status === 'IN_PROGRESS') && (
                              <Button
                                size="compact-xs"
                                variant="light"
                                color="edr-green"
                                leftSection={<CheckCircle2 size={13} />}
                                onClick={() => setCompleteTarget(m)}
                              >
                                Complete
                              </Button>
                            )}
                          </Table.Td>
                        </Table.Tr>
                      ))}
                    </Table.Tbody>
                  </Table>
                ) : (
                  <Text c="dimmed">No upcoming maintenance</Text>
                )}
              </Card.Section>
            </Card>
          </>
        )}
      </Stack>

      <Modal
        opened={openScheduleModal}
        onClose={() => setOpenScheduleModal(false)}
        title="Schedule Maintenance"
        size="md"
      >
        <Stack gap="md">
          <Select
            label="Type"
            data={['PREVENTIVE', 'CORRECTIVE', 'INSPECTION', 'REPAIR']}
            value={formData.maintenanceType}
            onChange={(v) => setFormData({ ...formData, maintenanceType: v || 'PREVENTIVE' })}
          />
          <TextInput
            label="Service item"
            placeholder="e.g. oil change — links this schedule to its interval"
            value={formData.serviceItem}
            onChange={(e) => setFormData({ ...formData, serviceItem: e.currentTarget.value })}
          />
          <TextInput
            label="Description"
            placeholder="What needs to be done?"
            value={formData.description}
            onChange={(e) => setFormData({ ...formData, description: e.currentTarget.value })}
          />
          <TextInput
            label="Scheduled Date"
            type="date"
            value={formData.scheduledDate}
            onChange={(e) => setFormData({ ...formData, scheduledDate: e.currentTarget.value })}
          />
          <NumberInput
            label="Estimated Cost"
            min={0}
            value={formData.estimatedCost}
            onChange={(v) => setFormData({ ...formData, estimatedCost: Number(v) })}
          />
          <TextInput
            label="Service Provider"
            placeholder="e.g., John's Auto Repair"
            value={formData.serviceProvider}
            onChange={(e) => setFormData({ ...formData, serviceProvider: e.currentTarget.value })}
          />
          <TextInput
            label="Notes"
            placeholder="Additional notes"
            value={formData.notes}
            onChange={(e) => setFormData({ ...formData, notes: e.currentTarget.value })}
          />
          <Group justify="flex-end">
            <Button variant="light" onClick={() => setOpenScheduleModal(false)}>
              Cancel
            </Button>
            <Button
              onClick={() => scheduleMutation.mutate()}
              loading={scheduleMutation.isPending}
              disabled={!selectedVehicle}
            >
              Schedule
            </Button>
          </Group>
        </Stack>
      </Modal>

      <Modal
        opened={completeTarget != null}
        onClose={() => setCompleteTarget(null)}
        title={`Complete maintenance${completeTarget?.serviceItem ? ` — ${completeTarget.serviceItem}` : ''}`}
        size="md"
      >
        <Stack gap="md">
          <Text size="sm" c="dimmed">
            Record the odometer at completion — the next service is auto-scheduled at reading +
            interval (e.g. completed at 50,000 km with a 10,000 km interval ⇒ next due at 60,000
            km).
          </Text>
          <NumberInput
            label="Odometer reading (km)"
            placeholder="e.g. 50000"
            min={0}
            required
            value={completeOdometer}
            onChange={(v) => setCompleteOdometer(v === '' ? '' : Number(v))}
          />
          <NumberInput
            label="Actual cost (ETB)"
            min={0}
            value={completeCost}
            onChange={(v) => setCompleteCost(v === '' ? '' : Number(v))}
          />
          <Group justify="flex-end">
            <Button variant="light" onClick={() => setCompleteTarget(null)}>
              Cancel
            </Button>
            <Button
              color="edr-green"
              leftSection={<CheckCircle2 size={15} />}
              loading={completeMutation.isPending}
              disabled={completeOdometer === ''}
              onClick={() => completeMutation.mutate()}
            >
              Complete & schedule next
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Container>
  );
}
