import { useState } from "react";
import {
  Badge,
  Button,
  FileButton,
  Group,
  Select,
  Stack,
  Text,
  Textarea,
} from "@mantine/core";
import { AlertTriangle, ImagePlus } from "lucide-react";
import type { Freight } from "@edr/types";

import {
  useBookingIncidents,
  useReportIncident,
} from "@/hooks/contracts/useContracts";
import { ActionShell } from "./ActionShell";

const INCIDENT_OPTIONS: { value: Freight.IncidentType; label: string }[] = [
  { value: "SEAL_BROKEN", label: "Seal is broken" },
  { value: "CONTAINER_OPENED", label: "Container opened" },
  { value: "CONTAINER_DAMAGED", label: "Container damaged" },
  { value: "FLUID_LEAKING", label: "Fluid leaking" },
  { value: "OTHER", label: "Other" },
];

const LABEL: Record<Freight.IncidentType, string> = {
  SEAL_BROKEN: "Seal broken",
  CONTAINER_OPENED: "Container opened",
  CONTAINER_DAMAGED: "Container damaged",
  FLUID_LEAKING: "Fluid leaking",
  OTHER: "Other",
};

export function IncidentReportCard({ bookingId }: { bookingId: string }) {
  const report = useReportIncident(bookingId);
  const { data: incidents } = useBookingIncidents(bookingId);
  const [type, setType] = useState<Freight.IncidentType>("SEAL_BROKEN");
  const [description, setDescription] = useState("");
  const [photos, setPhotos] = useState<File[]>([]);

  const submit = () => {
    if (!description.trim()) return;
    report.mutate(
      { incidentType: type, description: description.trim(), photos },
      {
        onSuccess: () => {
          setDescription("");
          setPhotos([]);
        },
      },
    );
  };

  return (
    <ActionShell
      icon={AlertTriangle}
      title="Cargo exception"
      subtitle="Log a damage/anomaly with photo evidence (GL Djibouti)."
    >
      <Stack gap="sm">
        {incidents && incidents.length > 0 ? (
          <Stack gap={4}>
            {incidents.map((inc) => (
              <Group key={inc.id} gap={8} wrap="nowrap">
                <Badge color="red" variant="light" radius="sm">
                  {LABEL[inc.incidentType]}
                </Badge>
                <Text size="xs" c="dimmed" truncate>
                  {inc.description}
                </Text>
              </Group>
            ))}
          </Stack>
        ) : null}

        <Select
          label="Incident type"
          data={INCIDENT_OPTIONS}
          value={type}
          onChange={(v) => setType((v as Freight.IncidentType) ?? "SEAL_BROKEN")}
          size="sm"
          allowDeselect={false}
        />
        <Textarea
          label="Description"
          placeholder="Describe the anomaly…"
          value={description}
          onChange={(e) => setDescription(e.currentTarget.value)}
          autosize
          minRows={2}
          size="sm"
        />
        <Group justify="space-between" wrap="nowrap">
          <FileButton onChange={setPhotos} accept="image/jpeg,image/png" multiple>
            {(props) => (
              <Button
                {...props}
                variant="light"
                color="gray"
                size="compact-sm"
                leftSection={<ImagePlus size={14} />}
              >
                {photos.length > 0 ? `${photos.length} photo(s)` : "Add photos"}
              </Button>
            )}
          </FileButton>
          <Button
            size="compact-sm"
            color="red"
            loading={report.isPending}
            disabled={!description.trim()}
            onClick={submit}
          >
            Report incident
          </Button>
        </Group>
      </Stack>
    </ActionShell>
  );
}
