import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Button,
  Card,
  Container,
  Group,
  Loader,
  Modal,
  NumberInput,
  Select,
  Stack,
  Table,
  Text,
  Textarea,
  TextInput,
  Title,
  Badge,
  Grid,
} from "@mantine/core";
import { Plus } from "lucide-react";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
import ListControls from "@/components/common/ListControls";
// Generic list footer — already shared by the fleet and train-scheduling lists
// despite the ruleEngine path.
import RuleEngineListFooter from "@/components/ruleEngine/RuleEngineListFooter";
import { useListControls } from "@/hooks/useListControls";
import { useToast } from "@/hooks/use-toast";
import {
  incidentsService,
  type Incident,
  type IncidentSeverity,
  type IncidentStatus,
  type IncidentType,
  type SaveIncidentPayload,
} from "@/services/incidents.service";
import { vehiclesService, type Vehicle as VehicleType } from "@/services/vehicles.service";
import { driversService, type Driver as DriverType } from "@/services/drivers.service";

const TYPE_OPTIONS: IncidentType[] = [
  "ACCIDENT",
  "BREAKDOWN",
  "TRAFFIC_VIOLATION",
  "THEFT",
  "OTHER",
];
const SEVERITY_OPTIONS: IncidentSeverity[] = ["MINOR", "MODERATE", "MAJOR", "CRITICAL"];

const TYPE_COLORS: Record<IncidentType, string> = {
  ACCIDENT: "red",
  BREAKDOWN: "orange",
  TRAFFIC_VIOLATION: "yellow",
  THEFT: "grape",
  OTHER: "gray",
};

const SEVERITY_COLORS: Record<IncidentSeverity, string> = {
  MINOR: "gray",
  MODERATE: "yellow",
  MAJOR: "orange",
  CRITICAL: "red",
};

const STATUS_COLORS: Record<IncidentStatus, string> = {
  REPORTED: "blue",
  UNDER_REVIEW: "yellow",
  CLAIM_FILED: "grape",
  RESOLVED: "teal",
  CLOSED: "gray",
};

const OPEN_STATUSES: IncidentStatus[] = ["REPORTED", "UNDER_REVIEW", "CLAIM_FILED"];

const formatMoney = (value: unknown) =>
  `ETB ${(Number(value) || 0).toLocaleString("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;

const initialForm = {
  type: "ACCIDENT" as IncidentType,
  severity: "MINOR" as IncidentSeverity,
  occurredAt: new Date().toISOString().split("T")[0],
  vehicleId: "",
  driverId: "",
  location: "",
  description: "",
  damageEstimate: undefined as number | undefined,
  reportedBy: "",
};

export default function IncidentsPage() {
  const { toast } = useToast();
  const qc = useQueryClient();
  const [modalOpen, setModalOpen] = useState(false);
  const [formData, setFormData] = useState(initialForm);

  // Fetch vehicles
  const { data: vehiclesData } = useQuery({
    queryKey: ["vehicles", "incidents-select"],
    queryFn: async () => {
      const res = await vehiclesService.getAll({ limit: 1000 });
      return res.data || [];
    },
  });

  // Fetch drivers
  const { data: driversData } = useQuery({
    queryKey: ["drivers", "incidents-select"],
    queryFn: async () => {
      const res = await driversService.getAll({ limit: 1000 });
      return res.data || [];
    },
  });

  // Fetch incidents
  const { data: incidentsData = [], isLoading } = useQuery({
    queryKey: ["incidents"],
    queryFn: async () => {
      const res = await incidentsService.getAll();
      return res.data || [];
    },
  });

  const createMutation = useMutation({
    mutationFn: async (data: typeof formData) => {
      const payload: SaveIncidentPayload = {
        type: data.type,
        severity: data.severity,
        occurredAt: new Date(data.occurredAt).toISOString(),
        description: data.description,
      };
      if (data.vehicleId) payload.vehicleId = data.vehicleId;
      if (data.driverId) payload.driverId = data.driverId;
      if (data.location) payload.location = data.location;
      if (data.damageEstimate != null) payload.damageEstimate = Number(data.damageEstimate);
      if (data.reportedBy) payload.reportedBy = data.reportedBy;
      const res = await incidentsService.create(payload);
      return res.data;
    },
    onSuccess: () => {
      toast({ title: "Incident reported" });
      setModalOpen(false);
      setFormData(initialForm);
      qc.invalidateQueries({ queryKey: ["incidents"] });
    },
    onError: (error: any) => {
      toast({
        title: "Error reporting incident",
        description: error?.response?.data?.message || "Failed to report incident",
        variant: "destructive",
      });
    },
  });

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

  const driverOptions =
    driversData?.map((d: DriverType) => ({
      value: d.id,
      label: `${d.firstName} ${d.lastName}${d.licenseNumber ? ` (${d.licenseNumber})` : ""}`,
    })) || [];

  const incidents = incidentsData as Incident[];
  const controls = useListControls(incidents, {
    searchKeys: ["type", "severity", "status"],
    dateKey: "occurredAt",
  });
  const totalCount = incidents.length;
  const openCount = incidents.filter((i) => OPEN_STATUSES.includes(i.status)).length;
  const underReviewCount = incidents.filter((i) => i.status === "UNDER_REVIEW").length;
  const resolvedCount = incidents.filter((i) => i.status === "RESOLVED").length;

  const vehicleLabel = (incident: Incident) =>
    incident.vehicle?.plateNumber ||
    incident.vehicle?.registrationNumber ||
    incident.vehicleId ||
    "—";

  const driverLabel = (incident: Incident) => {
    if (incident.driver) {
      const name = `${incident.driver.firstName ?? ""} ${incident.driver.lastName ?? ""}`.trim();
      if (name) return name;
    }
    return incident.driverId || "—";
  };

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

      <Group justify="space-between" mb="lg">
        <Title order={1}>Accidents &amp; Incidents</Title>
        <Button leftSection={<Plus size={16} />} onClick={() => setModalOpen(true)} color="edr-green">
          Report Incident
        </Button>
      </Group>

      {/* Stats Cards */}
      <Grid mb="lg">
        <Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
          <Card withBorder padding="lg">
            <Text size="sm" c="dimmed" fw={500}>
              Total Incidents
            </Text>
            <Text fw={700} size="lg">
              {totalCount}
            </Text>
          </Card>
        </Grid.Col>
        <Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
          <Card withBorder padding="lg">
            <Text size="sm" c="dimmed" fw={500}>
              Open
            </Text>
            <Text fw={700} size="lg">
              {openCount}
            </Text>
          </Card>
        </Grid.Col>
        <Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
          <Card withBorder padding="lg">
            <Text size="sm" c="dimmed" fw={500}>
              Under Review
            </Text>
            <Text fw={700} size="lg">
              {underReviewCount}
            </Text>
          </Card>
        </Grid.Col>
        <Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
          <Card withBorder padding="lg">
            <Text size="sm" c="dimmed" fw={500}>
              Resolved
            </Text>
            <Text fw={700} size="lg">
              {resolvedCount}
            </Text>
          </Card>
        </Grid.Col>
      </Grid>

      {/* Incidents Table */}
      <Card withBorder>
        <ListControls
          search={controls.search}
          onSearchChange={controls.setSearch}
          searchPlaceholder="Search type, severity, status…"
          dateFrom={controls.dateFrom}
          onDateFromChange={controls.setDateFrom}
          dateTo={controls.dateTo}
          onDateToChange={controls.setDateTo}
          dateLabel="Occurred"
          hasFilters={controls.hasFilters}
          onReset={controls.reset}
        />
        <Table striped highlightOnHover>
          <Table.Thead>
            <Table.Tr>
              <Table.Th>Date</Table.Th>
              <Table.Th>Type</Table.Th>
              <Table.Th>Severity</Table.Th>
              <Table.Th>Vehicle</Table.Th>
              <Table.Th>Driver</Table.Th>
              <Table.Th align="right">Damage</Table.Th>
              <Table.Th>Status</Table.Th>
            </Table.Tr>
          </Table.Thead>
          <Table.Tbody>
            {isLoading ? (
              <Table.Tr>
                <Table.Td colSpan={7}>
                  <Group justify="center" py="md">
                    <Loader size="sm" />
                  </Group>
                </Table.Td>
              </Table.Tr>
            ) : incidents.length === 0 ? (
              <Table.Tr>
                <Table.Td colSpan={7}>
                  <Text c="dimmed" ta="center" py="md">
                    No incidents recorded yet.
                  </Text>
                </Table.Td>
              </Table.Tr>
            ) : null}
            {controls.pagedRows.map((incident) => (
              <Table.Tr key={incident.id}>
                <Table.Td>{new Date(incident.occurredAt).toLocaleDateString()}</Table.Td>
                <Table.Td>
                  <Badge size="sm" color={TYPE_COLORS[incident.type]}>
                    {incident.type.replace(/_/g, " ")}
                  </Badge>
                </Table.Td>
                <Table.Td>
                  <Badge size="sm" color={SEVERITY_COLORS[incident.severity]}>
                    {incident.severity}
                  </Badge>
                </Table.Td>
                <Table.Td>{vehicleLabel(incident)}</Table.Td>
                <Table.Td>{driverLabel(incident)}</Table.Td>
                <Table.Td align="right">
                  {incident.damageEstimate != null ? formatMoney(incident.damageEstimate) : "—"}
                </Table.Td>
                <Table.Td>
                  <Badge size="sm" color={STATUS_COLORS[incident.status]} variant="light">
                    {incident.status.replace(/_/g, " ")}
                  </Badge>
                </Table.Td>
              </Table.Tr>
            ))}
          </Table.Tbody>
        </Table>
        <RuleEngineListFooter
          pagination={controls.pagination}
          pageCount={controls.pageCount}
          totalCount={controls.totalCount}
          itemLabel="incidents"
          onPaginationChange={controls.setPagination}
        />
      </Card>

      {/* Modal */}
      <Modal opened={modalOpen} onClose={() => setModalOpen(false)} title="Report Incident" size="lg">
        <Stack gap="md">
          <Select
            label="Type"
            data={TYPE_OPTIONS.map((t) => ({ value: t, label: t.replace(/_/g, " ") }))}
            value={formData.type}
            onChange={(val) => setFormData({ ...formData, type: (val as IncidentType) || "ACCIDENT" })}
            required
          />

          <Select
            label="Severity"
            data={SEVERITY_OPTIONS.map((s) => ({ value: s, label: s }))}
            value={formData.severity}
            onChange={(val) =>
              setFormData({ ...formData, severity: (val as IncidentSeverity) || "MINOR" })
            }
            required
          />

          <TextInput
            label="Occurred At"
            type="date"
            value={formData.occurredAt}
            onChange={(e) => setFormData({ ...formData, occurredAt: e.currentTarget.value })}
            required
          />

          <Select
            label="Vehicle"
            placeholder="Select vehicle"
            data={vehicleOptions}
            value={formData.vehicleId || null}
            onChange={(val) => setFormData({ ...formData, vehicleId: val || "" })}
            clearable
            searchable
          />

          <Select
            label="Driver"
            placeholder="Select driver"
            data={driverOptions}
            value={formData.driverId || null}
            onChange={(val) => setFormData({ ...formData, driverId: val || "" })}
            clearable
            searchable
          />

          <Textarea
            label="Description"
            placeholder="What happened?"
            value={formData.description}
            onChange={(e) => setFormData({ ...formData, description: e.currentTarget.value })}
            minRows={3}
            required
          />

          <NumberInput
            label="Damage Estimate (ETB)"
            placeholder="0.00"
            value={formData.damageEstimate}
            onChange={(val) =>
              setFormData({ ...formData, damageEstimate: val as number | undefined })
            }
            decimalScale={2}
            min={0}
            thousandSeparator=","
          />

          <TextInput
            label="Location"
            placeholder="Where did it happen?"
            value={formData.location}
            onChange={(e) => setFormData({ ...formData, location: e.currentTarget.value })}
          />

          <TextInput
            label="Reported By"
            placeholder="Optional"
            value={formData.reportedBy}
            onChange={(e) => setFormData({ ...formData, reportedBy: e.currentTarget.value })}
          />

          <Group justify="flex-end">
            <Button variant="light" onClick={() => setModalOpen(false)}>
              Cancel
            </Button>
            <Button
              onClick={() => createMutation.mutate(formData)}
              loading={createMutation.isPending}
              disabled={!formData.description.trim()}
            >
              Report Incident
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Container>
  );
}
