import { Box, Group, Stack, Switch, Text, TextInput } from "@mantine/core";
import type { ReactNode } from "react";
import {
  Check,
  Container,
  FileCheck2,
  FileText,
  Info,
  // PackageCheck,
  ShieldCheck,
  TrainFront,
  Truck,
} from "lucide-react";
import { useEffect, useMemo, useRef } from "react";
import { Controller, type UseFormReturn } from "react-hook-form";
import { ContractFormInputValues, type ContractFormValues } from "./schema";
import { filterBookableServices, operationToTradeDirection } from "./helpers";
import { fieldStyles, StepLabel } from "./shared";
import { LocationPicker } from "@/pages/bookings/new-booking-form/LocationPicker";

import type { Freight } from "@edr/types";

const GREEN = "#0A6F4D";
const GREEN_SOFT = "#F6FBF8";
const GREEN_RING = "#CDEBDD";
const BORDER = "#E6ECF2";
const INK = "#10202F";
const MUTED = "#6B7C8E";

type ServiceItem = Freight.BookingReferenceData["service"][number];

/** Feature chips describing what a service bundles, derived from its flags. */
function serviceFeatures(s: ServiceItem) {
  return [
    // { key: "rail", icon: TrainFront, label: "Rail haulage", on: true },
    // {
    //   key: "first",
    //   icon: Truck,
    //   label: "First mile pick-up",
    //   on: s.includesFirstMile,
    // },
    // {
    //   key: "last",
    //   icon: PackageCheck,
    //   label: "Last mile delivery",
    //   on: s.includesLastMile,
    // },
    {
      key: "customs",
      icon: ShieldCheck,
      label: "Customs clearance",
      on: s.includesCustoms,
    },
  ];
}

function FeatureChip({
  icon: Icon,
  label,
  on,
}: {
  icon: typeof TrainFront;
  label: string;
  on: boolean;
}) {
  return (
    <Group
      gap={5}
      wrap="nowrap"
      px={9}
      py={4}
      style={{
        borderRadius: 999,
        background: on ? "#ECF6F1" : "#F4F6F8",
        border: `1px solid ${on ? GREEN_RING : "#EDF1F5"}`,
        opacity: on ? 1 : 0.55,
      }}
    >
      <Icon size={12} color={on ? GREEN : "#9AA8B5"} strokeWidth={2.2} />
      <Text fz={11} fw={600} c={on ? GREEN : "#9AA8B5"} style={{ lineHeight: 1 }}>
        {label}
      </Text>
    </Group>
  );
}

/**
 * Premium card picker for the contract service type — replaces the plain
 * dropdown. Each selectable card shows the service name, description, and the
 * bundle it includes (rail / first mile / last mile / customs) as chips, with a
 * green ring + check on the active choice.
 */
function ServiceTypeSelector({
  services,
  value,
  onChange,
  onBlur,
  error,
}: {
  services: ServiceItem[];
  value: string | null;
  onChange: (id: string) => void;
  onBlur: () => void;
  error?: string;
}) {
  return (
    <Stack gap={8}>
      <Group justify="space-between" align="baseline">
        <Text fz={13} fw={600} c={INK}>
          Service Type <span style={{ color: "#E11D48" }}>*</span>
        </Text>
        {error ? (
          <Text fz={12} c="#E11D48" fw={600}>
            {error}
          </Text>
        ) : null}
      </Group>

      {services.length === 0 ? (
        <Box
          px={16}
          py={20}
          style={{
            borderRadius: 14,
            border: `1.5px dashed ${BORDER}`,
            background: "#FAFBFC",
            textAlign: "center",
          }}
        >
          <Text fz={13} c={MUTED}>
            No standalone services are available right now.
          </Text>
        </Box>
      ) : (
        <div className="grid gap-3 grid-cols-2 sm:grid-cols-3 lg:grid-cols-4">
          {services.map((s) => {
            const selected = s.id === value;
            return (
              <button
                key={s.id}
                type="button"
                onClick={() => {
                  onChange(s.id);
                  onBlur();
                }}
                style={{
                  position: "relative",
                  textAlign: "left",
                  cursor: "pointer",
                  padding: 12,
                  borderRadius: 14,
                  border: `1.5px solid ${selected ? GREEN : error ? "#F0B4B4" : BORDER}`,
                  background: selected ? GREEN_SOFT : "#fff",
                  boxShadow: selected
                    ? "0 8px 24px -12px rgba(10,111,77,0.45)"
                    : "0 1px 2px rgba(16,32,47,0.04)",
                  transition: "all 160ms cubic-bezier(0.4,0,0.2,1)",
                  outline: "none",
                }}
              >
                {/* Selected check */}
                <Box
                  style={{
                    position: "absolute",
                    top: 10,
                    right: 10,
                    width: 18,
                    height: 18,
                    borderRadius: 999,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: selected ? GREEN : "transparent",
                    border: selected ? "none" : `1.5px solid ${BORDER}`,
                    transition: "all 160ms ease",
                  }}
                >
                  {selected ? <Check size={11} color="#fff" strokeWidth={3} /> : null}
                </Box>

                <Group gap={9} align="flex-start" wrap="nowrap" mb={8}>
                  <Box
                    style={{
                      width: 34,
                      height: 34,
                      flexShrink: 0,
                      borderRadius: 10,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      background: selected ? "#ECF6F1" : "#F1F4F7",
                      color: selected ? GREEN : "#64748B",
                      transition: "all 160ms ease",
                    }}
                  >
                    <Container size={17} strokeWidth={2} />
                  </Box>
                  <Box style={{ minWidth: 0, paddingRight: 20 }}>
                    <Text fz={13} fw={700} c={INK} style={{ lineHeight: 1.25 }}>
                      {s.serviceName}
                    </Text>
                  </Box>
                </Group>

                <Group gap={6} wrap="wrap">
                  {serviceFeatures(s).map((f) => (
                    <FeatureChip
                      key={f.key}
                      icon={f.icon}
                      label={f.label}
                      on={f.on}
                    />
                  ))}
                </Group>
              </button>
            );
          })}
        </div>
      )}
    </Stack>
  );
}

type ContractForm = UseFormReturn<
  ContractFormInputValues,
  any,
  ContractFormValues
>;

export function Step2ServiceType({
  form,
  referenceData,
}: {
  form: ContractForm;
  referenceData?: Freight.BookingReferenceData;
}) {
  const serviceTypeId = form.watch("serviceTypeId");
  const operationType = form.watch("operationType");
  const serviceType = referenceData?.service.find(
    (s) => s.id === serviceTypeId,
  );

  const { includesCustoms } = serviceType ?? {};

  // Import contracts never truck the first mile (goods arrive at the port);
  // export contracts never truck the last mile. Hide the irrelevant toggle by
  // trade direction, regardless of what the service bundles.
  const tradeDirection = operationType
    ? operationToTradeDirection(operationType)
    : null;
  const includesFirstMile =
    (serviceType?.includesFirstMile ?? false) && tradeDirection !== "IMPORT";
  const includesLastMile =
    (serviceType?.includesLastMile ?? false) && tradeDirection !== "EXPORT";
  const firstMileEnabled = form.watch("firstMile.enabled");
  const lastMileEnabled = form.watch("lastMile.enabled");

  const prevServiceType = useRef(serviceType);
  useEffect(() => {
    const prev = prevServiceType.current;
    prevServiceType.current = serviceType;
    if (!prev || prev === serviceType) return;

    if (!includesFirstMile) {
      form.setValue(
        "firstMile",
        {
          enabled: false,
          pickUpAddress: "",
          exactLocation: "",
          lat: null,
          lng: null,
        },
        { shouldValidate: true },
      );
    }
    if (!includesLastMile) {
      form.setValue(
        "lastMile",
        {
          enabled: false,
          deliveryAddress: "",
          exactLocation: "",
          lat: null,
          lng: null,
        },
        { shouldValidate: true },
      );
    }

  }, [serviceType, includesFirstMile, includesLastMile, form]);

  // Customs clearance bundling is driven by the service: includesCustoms → the
  // contract follows Path B (clearance docs after sign); otherwise Path A.
  // Synced unconditionally — the prev-service guard above skips the very first
  // selection and restored drafts, which left customsClearingEnabled stale.
  useEffect(() => {
    const desired = Boolean(includesCustoms);
    if (form.getValues("customsClearingEnabled") !== desired) {
      form.setValue("customsClearingEnabled", desired, { shouldDirty: true });
    }
    // A bundled-customs service never carries a customer-named agent.
    if (desired && form.getValues("customsClearingAgent")) {
      form.setValue("customsClearingAgent", "", { shouldDirty: true });
    }
  }, [includesCustoms, form]);

  // A hidden mile must not leak a stale enabled=true into the payload. The
  // effect above only fires on service change; switching operation type (import
  // ⇄ export) hides a mile without touching the service, so clear it here too.
  useEffect(() => {
    if (!includesFirstMile && form.getValues("firstMile.enabled")) {
      form.setValue(
        "firstMile",
        { enabled: false, pickUpAddress: "", exactLocation: "", lat: null, lng: null },
        { shouldValidate: true },
      );
    }
    if (!includesLastMile && form.getValues("lastMile.enabled")) {
      form.setValue(
        "lastMile",
        { enabled: false, deliveryAddress: "", exactLocation: "", lat: null, lng: null },
        { shouldValidate: true },
      );
    }
  }, [includesFirstMile, includesLastMile, form]);

  const showServiceSections =
    serviceType != null || includesFirstMile || includesLastMile;

  const standaloneServices = useMemo(
    () => filterBookableServices(referenceData?.service, operationType),
    [referenceData, operationType],
  );

  useEffect(() => {
    // Skip right after a hydration `form.reset()` (edit mode) — a saved
    // contract's service is trusted as-is until the customer actually
    // changes something live; `isDirty` is false only in that pristine
    // post-hydration render, so this never clears a value nobody touched.
    if (!form.formState.isDirty) return;
    const currentId = form.getValues("serviceTypeId");
    if (!currentId) return;
    if (!standaloneServices.some((s) => s.id === currentId)) {
      form.setValue("serviceTypeId", "", { shouldValidate: true });
    }
  }, [operationType, standaloneServices, form]);

  // A contract is always quoted in USD now — the billing currency is chosen per
  // shipment (at booking, or on the shipment request when GL books). Intercity
  // still bills in ETB, but that is applied at booking time, not here.
  const isIntercity = operationType === "intercity";
  useEffect(() => {
    // The customs clearing agent field is hidden for intercity — drop any value
    // carried over from a draft or an operation-type switch.
    if (isIntercity && form.getValues("customsClearingAgent")) {
      form.setValue("customsClearingAgent", "", { shouldDirty: true });
    }
  }, [isIntercity, form]);

  return (
    <Stack gap={18}>
      <Controller
        name="serviceTypeId"
        control={form.control}
        render={({ field, fieldState }) => (
          <ServiceTypeSelector
            services={standaloneServices}
            value={field.value || null}
            onChange={(id) => field.onChange(id)}
            onBlur={field.onBlur}
            error={fieldState.error?.message}
          />
        )}
      />

      {showServiceSections && (
        <Stack gap={12}>
          <StepLabel>Trucking & customs options</StepLabel>

          {/* First mile, last mile and customs sit side by side on one wrapping
              row; each keeps a min width and stacks below on narrow screens. */}
          <div className="flex flex-wrap gap-3 [&>*]:flex-1 [&>*]:min-w-[280px]">
          {includesFirstMile && (
            <Controller
              name="firstMile.enabled"
              control={form.control}
              render={({ field }) => (
                <ServiceToggle
                  icon={<Truck size={18} />}
                  title="First Mile — Pick-up"
                  description="Truck pick-up from your premises (Door to Port) to the origin rail yard."
                  checked={field.value ?? false}
                  onChange={(value) => {
                    field.onChange(value);
                    if (!value) {
                      form.setValue(
                        "firstMile",
                        {
                          enabled: false,
                          pickUpAddress: "",
                          exactLocation: "",
                          lat: null,
                          lng: null,
                        },
                        { shouldDirty: true, shouldValidate: true },
                      );
                    }
                  }}
                >
                  {firstMileEnabled && (
                    <Stack mt="md" gap={12}>
                      <Controller
                        name="firstMile"
                        control={form.control}
                        render={({ field: mf, fieldState }) => (
                          <LocationPicker
                            variant="modal"
                            label="Pick-up location"
                            placeholder="Search the pick-up address…"
                            error={
                              (
                                fieldState.error as {
                                  pickUpAddress?: { message?: string };
                                }
                              )?.pickUpAddress?.message
                            }
                            value={{
                              address: mf.value?.pickUpAddress ?? "",
                              lat: mf.value?.lat ?? null,
                              lng: mf.value?.lng ?? null,
                            }}
                            onChange={(loc) =>
                              mf.onChange({
                                ...mf.value,
                                enabled: true,
                                pickUpAddress: loc.address,
                                lat: loc.lat,
                                lng: loc.lng,
                              })
                            }
                          />
                        )}
                      />
                      <Controller
                        name="firstMile.exactLocation"
                        control={form.control}
                        render={({ field: ef }) => (
                          <TextInput
                            label="Exact location (optional)"
                            placeholder="Gate, building, floor, landmark…"
                            value={ef.value ?? ""}
                            onChange={(e) => ef.onChange(e.currentTarget.value)}
                            radius={10}
                            styles={fieldStyles}
                          />
                        )}
                      />
                    </Stack>
                  )}
                </ServiceToggle>
              )}
            />
          )}

          {includesLastMile && (
            <Controller
              name="lastMile.enabled"
              control={form.control}
              render={({ field }) => (
                <ServiceToggle
                  icon={<Truck size={18} />}
                  title="Last Mile — Delivery"
                  description="Truck delivery from the destination rail yard to the final address (Port to Door)."
                  checked={field.value ?? false}
                  onChange={(value) => {
                    field.onChange(value);
                    if (!value) {
                      form.setValue(
                        "lastMile",
                        {
                          enabled: false,
                          deliveryAddress: "",
                          exactLocation: "",
                          lat: null,
                          lng: null,
                        },
                        { shouldDirty: true, shouldValidate: true },
                      );
                    }
                  }}
                >
                  {lastMileEnabled && (
                    <Stack mt="md" gap={12}>
                      <Controller
                        name="lastMile"
                        control={form.control}
                        render={({ field: mf, fieldState }) => (
                          <LocationPicker
                            variant="modal"
                            label="Delivery location"
                            placeholder="Search the delivery address…"
                            error={
                              (
                                fieldState.error as {
                                  deliveryAddress?: { message?: string };
                                }
                              )?.deliveryAddress?.message
                            }
                            value={{
                              address: mf.value?.deliveryAddress ?? "",
                              lat: mf.value?.lat ?? null,
                              lng: mf.value?.lng ?? null,
                            }}
                            onChange={(loc) =>
                              mf.onChange({
                                ...mf.value,
                                enabled: true,
                                deliveryAddress: loc.address,
                                lat: loc.lat,
                                lng: loc.lng,
                              })
                            }
                          />
                        )}
                      />
                      <Controller
                        name="lastMile.exactLocation"
                        control={form.control}
                        render={({ field: ef }) => (
                          <TextInput
                            label="Exact location (optional)"
                            placeholder="Gate, building, floor, landmark…"
                            value={ef.value ?? ""}
                            onChange={(e) => ef.onChange(e.currentTarget.value)}
                            radius={10}
                            styles={fieldStyles}
                          />
                        )}
                      />
                    </Stack>
                  )}
                </ServiceToggle>
              )}
            />
          )}


          {/* Intercity (domestic) moves never cross a border, so no customs
              clearing agent is collected. */}
          {isIntercity ? null : includesCustoms ? (
            <Box
              px={16}
              py={14}
              style={{
                borderRadius: 14,
                border: "1.5px solid #CDEBDD",
                background: "#F6FBF8",
              }}
            >
              <Group gap={13} align="flex-start" wrap="nowrap">
                <Box
                  style={{
                    width: 38,
                    height: 38,
                    flexShrink: 0,
                    borderRadius: 11,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: "#ECF6F1",
                    color: "#0A6F4D",
                  }}
                >
                  <FileCheck2 size={18} />
                </Box>
                <Box>
                  <Text fz={14} fw={700} c="#10202F">
                    Customs Clearing Service
                  </Text>
                  <Text fz={12} c="#6B7C8E" style={{ lineHeight: 1.4 }}>
                    Included with this service. After signing, upload your
                    clearance documents — Global Logistics reviews them, then you
                    create the booking.
                  </Text>
                </Box>
                <Box style={{ flexShrink: 0, marginLeft: "auto" }}>
                  <Group gap={6} align="center">
                    <Info size={14} color="#0A6F4D" />
                    <Text fz={12} fw={600} c="#0A6F4D">
                      Included
                    </Text>
                  </Group>
                </Box>
              </Group>
            </Box>
          ) : (
            <Controller
              name="customsClearingAgent"
              control={form.control}
              render={({ field, fieldState }) => (
                <Box
                  px={16}
                  py={14}
                  style={{
                    borderRadius: 14,
                    border: "1.5px solid #E6ECF2",
                    background: "#fff",
                  }}
                >
                  <Group gap={13} align="flex-start" wrap="nowrap" mb="sm">
                    <Box
                      style={{
                        width: 38,
                        height: 38,
                        flexShrink: 0,
                        borderRadius: 11,
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        background: "#F1F4F7",
                        color: "#64748B",
                      }}
                    >
                      <FileText size={18} />
                    </Box>
                    <Box>
                      <Text fz={14} fw={700} c="#10202F">
                        Customs Clearing Agent
                      </Text>
                      <Text fz={12} c="#6B7C8E" style={{ lineHeight: 1.4 }}>
                        Enter the name of your customs clearing agent for this
                        contract.
                      </Text>
                    </Box>
                  </Group>
                  <TextInput
                    {...field}
                    placeholder="Customs clearing agent name"
                    error={fieldState.error?.message}
                    radius={10}
                    styles={fieldStyles}
                  />
                </Box>
              )}
            />
          )}
          </div>
        </Stack>
      )}
    </Stack>
  );
}

function ServiceToggle({
  icon,
  title,
  description,
  checked,
  onChange,
  children,
}: {
  icon: ReactNode;
  title: string;
  description: string;
  checked: boolean;
  onChange: (v: boolean) => void;
  children?: ReactNode;
}) {
  return (
    <Box
      px={16}
      py={14}
      style={{
        borderRadius: 14,
        border: `1.5px solid ${checked ? "#CDEBDD" : "#E6ECF2"}`,
        background: checked ? "#F6FBF8" : "#fff",
        transition: "all 150ms ease",
      }}
    >
      <Group justify="space-between" align="flex-start" wrap="nowrap" gap={12}>
        <Group gap={13} align="flex-start" wrap="nowrap">
          <Box
            style={{
              width: 38,
              height: 38,
              flexShrink: 0,
              borderRadius: 11,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              background: checked ? "#ECF6F1" : "#F1F4F7",
              color: checked ? "#0A6F4D" : "#64748B",
            }}
          >
            {icon}
          </Box>
          <Box>
            <Text fz={14} fw={700} c="#10202F">
              {title}
            </Text>
            <Text fz={12} c="#6B7C8E" style={{ lineHeight: 1.4 }}>
              {description}
            </Text>
          </Box>
        </Group>
        <Switch
          checked={checked}
          onChange={(e) => onChange(e.currentTarget.checked)}
          color="edr-green"
          size="md"
          style={{ flexShrink: 0 }}
        />
      </Group>
      {children}
    </Box>
  );
}
