import { api } from "@/services/api";
import type { CreateBookingPayload } from "@/services/bookings.service";
import type { Freight } from "@edr/types";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  ActionIcon,
  Alert,
  Box,
  Button,
  Center,
  Divider,
  Group,
  Loader,
  Paper,
  SimpleGrid,
  Stack,
  Switch,
  Tabs,
  Text,
  Textarea,
  TextInput,
  Title,
} from "@mantine/core";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertCircle,
  AlertTriangle,
  Check,
  Download,
  FileText,
  Flame,
  MapPin,
  Snowflake,
  Truck,
  Upload,
  X,
} from "lucide-react";
import { useMemo, useRef, type ReactNode } from "react";
import { Controller, useForm } from "react-hook-form";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import {
  CountChip,
  DocRow,
  IconSquare,
} from "./BookingDetailPage/components/Documents";
import {
  BOOKING_DOCS_SETTING,
  BookingFormInputValues,
  bookingFormSchema,
  getRouteDirection,
  initialBookingFormValues,
  type BookingDocuments,
  type BookingFormValues,
} from "./new-booking-form/schema";
import { SelectField } from "./new-booking-form/shared";
import { LocationPicker } from "./new-booking-form/LocationPicker";
import { PaymentCurrencyField } from "./new-booking-form/payment-currency-field";
import { Step5CargoDetails, StepScheduling } from "./new-booking-form/steps";

const EDIT_SECTIONS = [
  "service",
  "route",
  "cargo",
  "schedule",
  "documents",
  "notes",
] as const;

type EditSection = (typeof EDIT_SECTIONS)[number];

function isEditSection(value: string | null): value is EditSection {
  return EDIT_SECTIONS.includes(value as EditSection);
}

function yardIdFromBooking(
  yard: Freight.IYard | null | undefined,
  referenceData: Freight.BookingReferenceData,
): string {
  if (yard?.id) return yard.id;
  const label = yard?.label ?? "";
  return (
    referenceData.yard.find((y) => y.name === label || y.id === label)?.id ?? ""
  );
}

/** Fallback container type for a size, used only when a booking row has no
 *  loaded containerType relation. */
function defaultContainerTypeForSize(
  referenceData: Freight.BookingReferenceData,
  size: string,
): string {
  const norm = (s: string) => s.toLowerCase().replace(/\s|ft/g, "");
  const group =
    referenceData.containers.find((g) => norm(g.size) === norm(size)) ??
    referenceData.containers[0];
  return group?.types[0]?.name ?? "";
}

/** The API returns the `bookingContainers` relation (with `containerType`
 *  loaded), not the `{ type, qty, vgm }` shape the frontend type advertises. */
interface BookingContainerRow {
  quantity: number;
  vgmPerUnitTons: number | string;
  containerType?: {
    sizeFt?: number | null;
    label?: string | null;
    code?: string | null;
  } | null;
}

function mapBookingToFormValues(
  booking: Freight.IBooking,
  referenceData: Freight.BookingReferenceData,
): BookingFormInputValues {
  const vals = {
    ...initialBookingFormValues,
    operationType:
      booking.tradeDirection === "IMPORT"
        ? "import"
        : booking.tradeDirection === "EXPORT"
          ? "export"
          : "intercity",
    contractType:
      (booking.contractType?.toLowerCase() as "new" | "renewal") ?? "new",
    previousContractRef: booking.previousContractId ?? "",
    serviceTypeId:
      referenceData.service.find((s) => s.code === booking.serviceType)?.id ?? "",
    firstMile: {
      enabled: booking.firstMileEnabled ?? false,
      pickUpAddress: booking.firstMilePickupAddress ?? "",
      lat: booking.firstMilePickupLat ?? null,
      lng: booking.firstMilePickupLng ?? null,
    },
    lastMile: {
      enabled: booking.lastMileEnabled ?? false,
      deliveryAddress: booking.lastMileDeliveryAddress ?? "",
      lat: booking.lastMileDeliveryLat ?? null,
      lng: booking.lastMileDeliveryLng ?? null,
    },
    customsClearingEnabled: booking.customsClearingEnabled ?? false,
    customsClearingAgent: booking.customsClearingAgent ?? "",
    equipmentReturn:
      booking.equipmentReturn === "WITH_RETURN"
        ? "with_return"
        : "without_return",
    originYard: yardIdFromBooking(booking.originYard, referenceData),
    destinationYard: yardIdFromBooking(booking.destinationYard, referenceData),
    cargoType: booking.freightType === "BULK" ? "bulk" : "container",
    cargoWeight: String(booking.cargoTotalWeightVgm ?? ""),
    isHazardous: booking.isHazardous ?? false,
    isRefrigerated: booking.isRefrigerated ?? false,
    paymentCurrency:
      booking.paymentCurrency === "ETB" ? "ETB" : "USD",
    scheduledDate: booking.scheduledDate
      ? new Date(booking.scheduledDate).toISOString().slice(0, 10)
      : "",
    notes: "",
    containers: [],
  } as BookingFormInputValues;

  const bookingCargoTypeId = (booking as any).cargoTypeId as string | undefined;
  if (booking.freightType === "BULK" && bookingCargoTypeId) {
    for (const group of referenceData.cargo_type) {
      const child = group.children?.find((c) => c.id === bookingCargoTypeId);
      if (child) {
        vals.cargoTypePath = [group.id, child.id];
        break;
      }
    }
  }

  if (booking.freightType === "CONTAINER") {
    const rows = ((booking as any).bookingContainers ?? []) as BookingContainerRow[];
    vals.containers =
      rows.length > 0
        ? rows.map((bc) => {
            const size =
              bc.containerType?.sizeFt === 40
                ? ("40ft" as const)
                : ("20ft" as const);
            const typeName = bc.containerType?.label?.trim()
              ? bc.containerType.label
              : (bc.containerType?.code ??
                defaultContainerTypeForSize(referenceData, size));
            return {
              type: size,
              containerType: typeName,
              qty: String(bc.quantity ?? 1),
              vgm: String(Number(bc.vgmPerUnitTons ?? 0)),
            };
          })
        : [
            {
              type: "20ft" as const,
              containerType: defaultContainerTypeForSize(referenceData, "20ft"),
              qty: "1",
              vgm: "",
            },
          ];
  }

  return vals;
}

function SectionHeading({
  title,
  description,
}: {
  title: string;
  description: string;
}) {
  return (
    <Box>
      <Title order={2} fz="lg" fw={700}>
        {title}
      </Title>
      <Text size="sm" c="dimmed" mt={2}>
        {description}
      </Text>
    </Box>
  );
}

function ToggleRow({
  icon,
  title,
  description,
  checked,
  onChange,
  children,
}: {
  icon: ReactNode;
  title: string;
  description: string;
  checked: boolean;
  onChange: (value: boolean) => void;
  children?: ReactNode;
}) {
  return (
    <Box p="md">
      <Group justify="space-between" align="flex-start" wrap="nowrap" gap="md">
        <Group align="flex-start" gap="sm" wrap="nowrap">
          <Box mt={2}>{icon}</Box>
          <Box>
            <Text size="sm" fw={500}>
              {title}
            </Text>
            <Text size="xs" c="dimmed" mt={2}>
              {description}
            </Text>
          </Box>
        </Group>
        <Switch
          checked={checked}
          onChange={(e) => onChange(e.currentTarget.checked)}
          color="edr-green"
        />
      </Group>
      {children}
    </Box>
  );
}

const DIRECTION_COLOR: Record<string, string> = {
  export: "blue",
  import: "yellow",
  domestic: "gray",
};
const DIRECTION_LABEL: Record<string, string> = {
  export: "Export workflow (inside country to outside country)",
  import: "Import workflow (outside country to inside country)",
  domestic: "Domestic corridor",
};

export default function EditBookingPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const queryClient = useQueryClient();
  const docInputRefs = useRef<Record<string, HTMLInputElement | null>>({});

  const sectionParam = searchParams.get("section");
  const activeSection: EditSection = isEditSection(sectionParam)
    ? sectionParam
    : "service";

  function setSection(section: EditSection) {
    setSearchParams({ section });
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  const bookingQuery = useQuery(
    api.bookings.get.queryOptions({
      input: { id: id! },
      enabled: !!id,
    }),
  );

  const { data: referenceData } = useQuery(
    api.bookings.referenceData.queryOptions({
      enabled: !!bookingQuery.data,
    }),
  );

  const booking = bookingQuery.data;

  const formValues = useMemo((): BookingFormInputValues | undefined => {
    if (!booking || !referenceData) return undefined;
    return mapBookingToFormValues(booking, referenceData);
  }, [booking, referenceData]);

  const form = useForm<BookingFormInputValues, any, BookingFormValues>({
    defaultValues: initialBookingFormValues,
    values: formValues,
    resolver: zodResolver(bookingFormSchema),
    mode: "onChange",
  });

  const updateMutation = useMutation({
    mutationFn: async (payload: Partial<CreateBookingPayload>) => {
      const documents = (form.getValues("documents") ?? {}) as BookingDocuments;
      const newDocuments: BookingDocuments = {};
      for (const [key, value] of Object.entries(documents)) {
        if (value) newDocuments[key] = value;
      }
      return api.bookings.update.call({
        id: id!,
        dto: payload,
        documents:
          Object.keys(newDocuments).length > 0 ? newDocuments : undefined,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: api.bookings.list.queryKey() });
      queryClient.invalidateQueries({
        queryKey: api.bookings.get.queryKey({ id: id! }),
      });
      navigate(`/bookings/${id}`);
    },
  });

  const originYard = form.watch("originYard");
  const destinationYard = form.watch("destinationYard");
  const serviceTypeId = form.watch("serviceTypeId");
  const firstMileEnabled = form.watch("firstMile.enabled");
  const lastMileEnabled = form.watch("lastMile.enabled");
  const customsClearingEnabled = form.watch("customsClearingEnabled");
  const documents = (form.watch("documents") ?? {}) as BookingDocuments;

  const selectedService = useMemo(
    () => referenceData?.service.find((s) => s.id === serviceTypeId),
    [serviceTypeId, referenceData],
  );
  const showFirstMile = Boolean(
    selectedService?.includesFirstMile && firstMileEnabled,
  );
  const showLastMile = Boolean(
    selectedService?.includesLastMile && lastMileEnabled,
  );

  const direction = useMemo(() => {
    const origin = referenceData?.yard.find((y) => y.id === originYard);
    const destination = referenceData?.yard.find(
      (y) => y.id === destinationYard,
    );
    return getRouteDirection(origin, destination);
  }, [originYard, destinationYard, referenceData]);

  const yardOptions = useMemo(() => {
    if (!referenceData?.yard) return [];
    return referenceData.yard.map((y) => ({
      value: y.id,
      label: y.name,
      country: y.country,
    }));
  }, [referenceData]);

  const setDocument = (key: string, file: File | null) => {
    const current = (form.getValues("documents") ?? {}) as BookingDocuments;
    form.setValue(
      "documents",
      { ...current, [key]: file },
      { shouldDirty: true },
    );
  };

  const handleSubmit = form.handleSubmit((data) => {
    const containerGroups = referenceData?.containers ?? [];

    const cargoTypePath = data.cargoTypePath ?? [];
    const cargoTypeId =
      data.cargoType === "container" ? undefined : (cargoTypePath[1] ?? "");

    const findContainerTypeId = (name: string): string => {
      for (const group of containerGroups) {
        const ct = group.types.find((t) => t.name === name);
        if (ct) return ct.id;
      }
      return "";
    };

    const totalWeight =
      data.cargoType === "container"
        ? data.containers.reduce(
            (acc, c) => acc + Number(c.vgm || 0) * Number(c.qty || 0),
            0,
          )
        : Number(data.cargoWeight || 0);

    const selectedSvc = referenceData?.service.find(
      (s) => s.id === data.serviceTypeId,
    );

    const apiPayload: Partial<CreateBookingPayload> = {
      scheduledDate: data.scheduledDate
        ? new Date(data.scheduledDate).toISOString()
        : undefined,
      // Day-level pool: the customer edits only the day; the engine assigns the
      // train, so trainScheduleId is not sent.
      contractType:
        data.contractType.toUpperCase() as CreateBookingPayload["contractType"],
      serviceTypeId: data.serviceTypeId,
      equipmentReturn:
        data.equipmentReturn === "with_return"
          ? "WITH_RETURN"
          : "WITHOUT_RETURN",
      originYardId: data.originYard,
      destinationYardId: data.destinationYard,
      tradeDirection:
        direction === "EXPORT"
          ? "EXPORT"
          : direction === "DOMESTIC"
            ? "DOMESTIC"
            : "IMPORT",
      cargoTypeId: data.cargoType === "container" ? undefined : cargoTypeId,
      cargoTotalWeightVgm: totalWeight,
      isHazardous: data.isHazardous,
      paymentCurrency: data.paymentCurrency,
      freightType:
        data.cargoType === "container"
          ? ("CONTAINER" as const)
          : ("BULK" as const),
      containers:
        data.cargoType === "container"
          ? data.containers.map((c) => ({
              containerTypeId: findContainerTypeId(c.containerType),
              quantity: Number(c.qty || 1),
              vgmPerUnitTons: Number(c.vgm || 0),
            }))
          : [],
      ...(data.previousContractRef
        ? { previousContractId: data.previousContractRef }
        : {}),
      ...(data.contractType === "renewal" && data.previousContractRef
        ? { pnrCode: data.previousContractRef }
        : {}),
      ...(selectedSvc?.includesFirstMile && data.firstMile.enabled
        ? {
            firstMilePickupAddress: data.firstMile.pickUpAddress,
            firstMilePickupLat: data.firstMile.lat ?? undefined,
            firstMilePickupLng: data.firstMile.lng ?? undefined,
          }
        : {}),
      ...(selectedSvc?.includesLastMile && data.lastMile.enabled
        ? {
            lastMileDeliveryAddress: data.lastMile.deliveryAddress,
            lastMileDeliveryLat: data.lastMile.lat ?? undefined,
            lastMileDeliveryLng: data.lastMile.lng ?? undefined,
          }
        : {}),
      ...(selectedSvc?.includesCustoms && data.customsClearingEnabled
        ? {
            customsClearingEnabled: true,
            customsClearingAgent: data.customsClearingAgent,
          }
        : { customsClearingEnabled: false }),
    };

    updateMutation.mutate(apiPayload);
  });

  if (bookingQuery.isLoading) {
    return (
      <Center mih={400} p="xl">
        <Stack align="center" gap="md">
          <Loader color="edr-green" />
          <Text size="sm" c="dimmed">
            Loading booking…
          </Text>
        </Stack>
      </Center>
    );
  }

  if (bookingQuery.isError || !booking) {
    return (
      <Center mih={400} p="xl">
        <Stack align="center" gap="md" ta="center">
          <Box c="red">
            <AlertTriangle size={30} />
          </Box>
          <Text fw={700} fz="lg">
            Failed to load booking
          </Text>
          <Button variant="default" onClick={() => navigate("/bookings")}>
            Back to Bookings
          </Button>
        </Stack>
      </Center>
    );
  }

  if (!formValues) {
    return (
      <Center mih={400} p="xl">
        <Loader color="edr-green" />
      </Center>
    );
  }

  const uploadedCodes = new Set(
    booking.files?.map((f) => f.code).filter(Boolean) ?? [],
  );
  const uploadedCount = BOOKING_DOCS_SETTING.fields.filter((f) =>
    uploadedCodes.has(f.fileKey),
  ).length;

  return (
    <Box
      component="form"
      id="edit-booking-form"
      onSubmit={handleSubmit}
      maw={900}
      mx="auto"
      px="md"
      py="xl"
    >
      <Title order={1} fz={26} fw={800} style={{ letterSpacing: "-0.01em" }}>
        Edit Booking {booking.reference ?? ""}
      </Title>
      <Text size="sm" c="dimmed" mt={4}>
        Update the booking details below. All changes are saved together.
      </Text>

      {updateMutation.isError && (
        <Alert
          color="red"
          icon={<AlertCircle size={16} />}
          radius="md"
          mt="lg"
          title="Failed to save changes"
        >
          <Text size="sm">
            {updateMutation.error instanceof Error
              ? updateMutation.error.message
              : "An unexpected error occurred. Please try again."}
          </Text>
        </Alert>
      )}

      {booking.status === "CHANGES_REQUESTED" && (
        <Alert color="orange" icon={<AlertCircle size={16} />} radius="md" mt="lg">
          <Text size="sm" fw={600}>
            Staff requested changes
          </Text>
          <Text size="sm" mt={4}>
            Update the sections below and save. Then return to the booking page to
            resubmit for review.
          </Text>
        </Alert>
      )}

      <Tabs
        value={activeSection}
        onChange={(value) => value && setSection(value as EditSection)}
        mt="xl"
      >
        <Tabs.List mb="lg" style={{ flexWrap: "wrap" }}>
          <Tabs.Tab value="service">Service</Tabs.Tab>
          <Tabs.Tab value="route">Route</Tabs.Tab>
          <Tabs.Tab value="cargo">Cargo</Tabs.Tab>
          <Tabs.Tab value="schedule">Schedule</Tabs.Tab>
          <Tabs.Tab value="documents">Documents</Tabs.Tab>
          <Tabs.Tab value="notes">Notes</Tabs.Tab>
        </Tabs.List>

        <Tabs.Panel value="service">
      <Stack gap="md">
          <SectionHeading
            title="Service"
            description="Select the service combination and configure trucking options."
          />

          <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
            <Controller
              name="serviceTypeId"
              control={form.control}
              render={({ field, fieldState }) => (
                <SelectField
                  field={field}
                  error={fieldState.error}
                  label="Service Type *"
                  placeholder="Select service type..."
                  data={(referenceData?.service ?? [])
                    .filter((s) => s.canBeBookedAlone)
                    .map((s) => ({ value: s.id, label: s.serviceName }))}
                />
              )}
            />

            <Controller
              name="equipmentReturn"
              control={form.control}
              render={({ field, fieldState }) => (
                <SelectField
                  field={field}
                  error={fieldState.error}
                  label="Equipment Return"
                  placeholder="Select..."
                  data={[
                    { value: "with_return", label: "With Return" },
                    { value: "without_return", label: "Without Return" },
                  ]}
                />
              )}
            />
          </SimpleGrid>

          <PaymentCurrencyField control={form.control} />

          {(selectedService?.includesFirstMile ||
            selectedService?.includesLastMile ||
            selectedService?.includesCustoms) && (
            <Paper withBorder radius="md">
              <Controller
                name="firstMile.enabled"
                control={form.control}
                render={({ field }) => (
                  <ToggleRow
                    icon={<Truck size={16} color="#6B7C8E" />}
                    title="First Mile - Pick-up"
                    description="Truck pick-up from your premises to the origin rail yard."
                    checked={field.value ?? false}
                    onChange={(value) => {
                      field.onChange(value);
                      if (!value) {
                        form.setValue(
                          "firstMile",
                          { enabled: false, pickUpAddress: "", lat: null, lng: null },
                          { shouldDirty: true, shouldValidate: true },
                        );
                      }
                    }}
                  >
                    {firstMileEnabled && (
                      <Text fz={12} c="#6B7C8E" mt="sm">
                        Set the exact pick-up location on the map in the Route
                        tab.
                      </Text>
                    )}
                  </ToggleRow>
                )}
              />

              <Divider />

              <Controller
                name="lastMile.enabled"
                control={form.control}
                render={({ field }) => (
                  <ToggleRow
                    icon={<Truck size={16} color="#6B7C8E" />}
                    title="Last Mile - Delivery"
                    description="Truck delivery from the destination rail yard to the final address."
                    checked={field.value ?? false}
                    onChange={(value) => {
                      field.onChange(value);
                      if (!value) {
                        form.setValue(
                          "lastMile",
                          { enabled: false, deliveryAddress: "", lat: null, lng: null },
                          { shouldDirty: true, shouldValidate: true },
                        );
                      }
                    }}
                  >
                    {lastMileEnabled && (
                      <Text fz={12} c="#6B7C8E" mt="sm">
                        Set the exact delivery location on the map in the Route
                        tab.
                      </Text>
                    )}
                  </ToggleRow>
                )}
              />

              <Divider />

              <Controller
                name="customsClearingEnabled"
                control={form.control}
                render={({ field }) => (
                  <ToggleRow
                    icon={<FileText size={16} color="#6B7C8E" />}
                    title="Customs Clearing Service"
                    description="EDR handles customs documentation and clearance on your behalf."
                    checked={field.value ?? false}
                    onChange={(value) => {
                      field.onChange(value);
                      if (!value) {
                        form.setValue("customsClearingAgent", "", {
                          shouldDirty: true,
                          shouldValidate: true,
                        });
                      }
                    }}
                  >
                    {customsClearingEnabled && (
                      <Controller
                        name="customsClearingAgent"
                        control={form.control}
                        render={({ field: agent, fieldState }) => (
                          <TextInput
                            {...agent}
                            mt="sm"
                            radius="md"
                            placeholder="Customs clearing agent *"
                            error={fieldState.error?.message}
                          />
                        )}
                      />
                    )}
                  </ToggleRow>
                )}
              />
            </Paper>
          )}
        </Stack>
        </Tabs.Panel>

        <Tabs.Panel value="route">
        <Stack gap="md">
          <SectionHeading
            title="Route"
            description="Select the origin and destination yards."
          />

          <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
            <Controller
              name="originYard"
              control={form.control}
              render={({ field, fieldState }) => (
                <SelectField
                  field={field}
                  error={fieldState.error}
                  label="Origin Yard *"
                  placeholder="Select origin..."
                  disabled={yardOptions.length === 0}
                  data={yardOptions.filter((y) => y.value !== destinationYard)}
                />
              )}
            />

            <Controller
              name="destinationYard"
              control={form.control}
              render={({ field, fieldState }) => (
                <SelectField
                  field={field}
                  error={fieldState.error}
                  label="Destination Yard *"
                  placeholder="Select destination..."
                  disabled={yardOptions.length === 0}
                  data={yardOptions.filter((y) => y.value !== originYard)}
                />
              )}
            />
          </SimpleGrid>

          {direction && (
            <Alert
              color={DIRECTION_COLOR[direction]}
              icon={<MapPin size={16} />}
              radius="md"
            >
              {DIRECTION_LABEL[direction]}
            </Alert>
          )}

          {(showFirstMile || showLastMile) && (
            <Stack gap="md">
              <SectionHeading
                title="Trucking locations"
                description="Search an address or click the map to drop a pin for your door-to-port and port-to-door trucking."
              />
              {showFirstMile && (
                <Controller
                  name="firstMile"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <LocationPicker
                      label="First mile — pick-up location"
                      placeholder="Search the pick-up address…"
                      error={
                        (fieldState.error as { pickUpAddress?: { message?: string } })
                          ?.pickUpAddress?.message
                      }
                      value={{
                        address: field.value?.pickUpAddress ?? "",
                        lat: field.value?.lat ?? null,
                        lng: field.value?.lng ?? null,
                      }}
                      onChange={(loc) =>
                        field.onChange({
                          ...field.value,
                          enabled: true,
                          pickUpAddress: loc.address,
                          lat: loc.lat,
                          lng: loc.lng,
                        })
                      }
                    />
                  )}
                />
              )}
              {showLastMile && (
                <Controller
                  name="lastMile"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <LocationPicker
                      label="Last mile — delivery location"
                      placeholder="Search the delivery address…"
                      error={
                        (fieldState.error as { deliveryAddress?: { message?: string } })
                          ?.deliveryAddress?.message
                      }
                      value={{
                        address: field.value?.deliveryAddress ?? "",
                        lat: field.value?.lat ?? null,
                        lng: field.value?.lng ?? null,
                      }}
                      onChange={(loc) =>
                        field.onChange({
                          ...field.value,
                          enabled: true,
                          deliveryAddress: loc.address,
                          lat: loc.lat,
                          lng: loc.lng,
                        })
                      }
                    />
                  )}
                />
              )}
            </Stack>
          )}

          <Paper withBorder radius="md">
            <Controller
              name="isHazardous"
              control={form.control}
              render={({ field }) => (
                <ToggleRow
                  icon={<Flame size={16} color="#E03131" />}
                  title="Hazardous Material"
                  description="Applies a Hazard Surcharge to the final bill."
                  checked={field.value}
                  onChange={field.onChange}
                />
              )}
            />
            <Divider />
            <Controller
              name="isRefrigerated"
              control={form.control}
              render={({ field }) => (
                <ToggleRow
                  icon={<Snowflake size={16} color="#1C7ED6" />}
                  title="Refrigerated Cargo"
                  description="Temperature-controlled transport applies a Refrigerator Surcharge."
                  checked={field.value}
                  onChange={field.onChange}
                />
              )}
            />
          </Paper>
        </Stack>
        </Tabs.Panel>

        <Tabs.Panel value="cargo">
        <Box>
          <Step5CargoDetails
            form={form}
            referenceData={referenceData}
            isLoading={!referenceData}
          />
        </Box>
        </Tabs.Panel>

        <Tabs.Panel value="schedule">
          <StepScheduling form={form} referenceData={referenceData} />
        </Tabs.Panel>

        <Tabs.Panel value="documents">
        <Stack gap="md">
          <SectionHeading
            title="Documents"
            description="Attach or replace shipment documents. Uploads are saved when you save your changes."
          />

          <Paper withBorder radius="md" p="md">
            <Group justify="space-between" align="center" mb="xs">
              <Text fw={700} fz="sm" c="#10202F">
                Shipment documents
              </Text>
              <CountChip
                uploaded={uploadedCount}
                total={BOOKING_DOCS_SETTING.fields.length}
              />
            </Group>

            <Box>
              {BOOKING_DOCS_SETTING.fields.map((docField, i) => {
                const isUploaded = uploadedCodes.has(docField.fileKey);
                const uploadedFile = booking.files?.find(
                  (f) => f.code === docField.fileKey,
                );
                const value = documents[docField.fileKey];
                const selected = value instanceof File ? value : null;

                return (
                  <DocRow
                    key={docField.fileKey}
                    last={i === BOOKING_DOCS_SETTING.fields.length - 1}
                    title={docField.fileLabel}
                    meta={
                      selected
                        ? selected.name
                        : isUploaded
                          ? (uploadedFile?.name ?? "Uploaded")
                          : "Not added yet"
                    }
                    status={
                      selected ? "ready" : isUploaded ? "verified" : "missing"
                    }
                    action={
                      <Group gap={6} wrap="nowrap">
                        {isUploaded && !selected && (
                          <IconSquare
                            href={uploadedFile?.signedUrl ?? uploadedFile?.url}
                            icon={<Download size={16} />}
                          />
                        )}
                        <input
                          ref={(el) => {
                            docInputRefs.current[docField.fileKey] = el;
                          }}
                          type="file"
                          accept=".pdf,.jpg,.jpeg,.png"
                          style={{ display: "none" }}
                          onChange={(e) =>
                            setDocument(
                              docField.fileKey,
                              e.target.files?.[0] ?? null,
                            )
                          }
                        />
                        <Button
                          variant="default"
                          size="xs"
                          radius="md"
                          leftSection={<Upload size={14} />}
                          onClick={() =>
                            docInputRefs.current[docField.fileKey]?.click()
                          }
                        >
                          {selected ? "Change" : isUploaded ? "Replace" : "Add"}
                        </Button>
                        {selected && (
                          <ActionIcon
                            variant="default"
                            radius="md"
                            color="red"
                            onClick={() => setDocument(docField.fileKey, null)}
                            aria-label="Discard replacement"
                          >
                            <X size={15} />
                          </ActionIcon>
                        )}
                      </Group>
                    }
                  />
                );
              })}
            </Box>
          </Paper>
        </Stack>
        </Tabs.Panel>

        <Tabs.Panel value="notes">
        <Stack gap="md">
          <SectionHeading
            title="Notes"
            description="Add any special instructions for EDR operations."
          />
          <Controller
            name="notes"
            control={form.control}
            render={({ field }) => (
              <Textarea
                {...field}
                radius="md"
                label="Additional Notes"
                placeholder="Any special instructions or notes for EDR operations..."
                rows={3}
              />
            )}
          />
        </Stack>
        </Tabs.Panel>
      </Tabs>

      {/* ── Submit ── */}
      <Group
        mt="xl"
        pt="lg"
        gap="sm"
        style={{ borderTop: "1px solid var(--mantine-color-gray-2)" }}
      >
        <Button
          type="button"
          variant="default"
          radius="md"
          onClick={() => navigate(`/bookings/${id}`)}
        >
          Cancel
        </Button>
        <Button
          type="submit"
          form="edit-booking-form"
          color="edr-green"
          radius="md"
          loading={updateMutation.isPending}
          leftSection={
            updateMutation.isPending ? undefined : <Check size={16} />
          }
        >
          {updateMutation.isPending ? "Saving Changes..." : "Save Changes"}
        </Button>
      </Group>
    </Box>
  );
}
