import { Box, Group, Stack, Switch, Text, TextInput } from "@mantine/core";
import type { ReactNode } from "react";
import { FileText, Layers, Train, Truck } from "lucide-react";
import { useEffect, useRef } from "react";
import { Controller, type UseFormReturn } from "react-hook-form";
import { BookingFormInputValues, type BookingFormValues } from "./schema";
import {
  fieldStyles,
  OptionCard,
  OptionFieldError,
  StepCard,
  StepHeader,
  StepLabel,
} from "./shared";
import { PaymentCurrencyField } from "./payment-currency-field";
import { LocationPicker } from "./LocationPicker";

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

type BookingForm = UseFormReturn<
  BookingFormInputValues,
  any,
  BookingFormValues
>;

export function Step2ServiceType({
  form,
  referenceData,
}: {
  form: BookingForm;

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

  const { includesCustoms, includesFirstMile, includesLastMile } =
    serviceType ?? {};
  const firstMileEnabled = form.watch("firstMile.enabled");
  const lastMileEnabled = form.watch("lastMile.enabled");
  const customsClearingEnabled = form.watch("customsClearingEnabled");

  const prevServiceType = useRef(serviceType);
  useEffect(() => {
    form.setValue(
      "firstMile",
      { enabled: false, pickUpAddress: "", lat: null, lng: null },
      { shouldValidate: true },
    );
  }, [includesFirstMile]);

  useEffect(() => {
    form.setValue(
      "lastMile",
      { enabled: false, deliveryAddress: "", lat: null, lng: null },
      { shouldValidate: true },
    );
  }, [includesLastMile]);

  useEffect(() => {
    const prev = prevServiceType.current;
    prevServiceType.current = serviceType;

    if (!prev || prev === serviceType) return;

    if (!includesCustoms)
      form.setValue("customsClearingEnabled", false, { shouldDirty: true });
  }, [serviceTypeId, form]);

  const showServiceSections =
    includesCustoms || includesFirstMile || includesLastMile;
  return (
    <StepCard>
      <StepHeader
        icon={<Layers size={22} />}
        title="Service Type"
        description="Choose the service combination, then configure your trucking options."
      />

      <Controller
        name="serviceTypeId"
        control={form.control}
        render={({ field, fieldState }) => (
          <div>
            <div className="grid gap-4 md:grid-cols-2">
              {referenceData?.service
                .filter((s) => s.canBeBookedAlone)
                .map((s) => (
                  <OptionCard
                    key={s.id}
                    selected={field.value === s.id}
                    onClick={() => field.onChange(s.id)}
                    icon={<Train className="h-5 w-5" />}
                    iconBg="#EEF0FB"
                    iconColor="#4F46E5"
                    title={s.serviceName}
                    description={s.description}
                  />
                ))}
            </div>
            <OptionFieldError error={fieldState.error} />
          </div>
        )}
      />

      <PaymentCurrencyField control={form.control} />

      {showServiceSections && (
        <Stack gap={12} mt={24}>
          <StepLabel>Trucking & customs options</StepLabel>
          {/* First Mile */}
          {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) {
                      // Toggling off clears the captured pick-up location below.
                      form.setValue(
                        "firstMile",
                        { enabled: false, pickUpAddress: "", lat: null, lng: null },
                        { shouldDirty: true, shouldValidate: true },
                      );
                    }
                  }}
                >
                  {firstMileEnabled && (
                    <Box mt="md">
                      <Controller
                        name="firstMile"
                        control={form.control}
                        render={({ field: mf, fieldState }) => (
                          <LocationPicker
                            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,
                              })
                            }
                          />
                        )}
                      />
                    </Box>
                  )}
                </ServiceToggle>
              )}
            />
          )}

          {/* Last Mile */}
          {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) {
                      // Toggling off clears the captured delivery location below.
                      form.setValue(
                        "lastMile",
                        { enabled: false, deliveryAddress: "", lat: null, lng: null },
                        { shouldDirty: true, shouldValidate: true },
                      );
                      form.setValue("equipmentReturn", "with_return", {
                        shouldDirty: true,
                      });
                    }
                  }}
                >
                  {lastMileEnabled && (
                    <Box mt="md">
                      <Controller
                        name="lastMile"
                        control={form.control}
                        render={({ field: mf, fieldState }) => (
                          <LocationPicker
                            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,
                              })
                            }
                          />
                        )}
                      />
                    </Box>
                  )}
                </ServiceToggle>
              )}
            />
          )}

          {/* Equipment Return */}
          {includesLastMile && lastMileEnabled && (
            <Controller
              name="equipmentReturn"
              control={form.control}
              render={({ field }) => (
                <ServiceToggle
                  icon={<Truck size={18} />}
                  title="Equipment Return"
                  description={
                    field.value === "with_return"
                      ? "Container returned to EDR after unloading."
                      : "Container retained by the customer after delivery."
                  }
                  checked={field.value === "with_return"}
                  onChange={(v) =>
                    field.onChange(v ? "with_return" : "without_return")
                  }
                />
              )}
            />
          )}

          {/* Customs Clearing */}
          {includesCustoms && (
            <Controller
              name="customsClearingEnabled"
              control={form.control}
              render={({ field }) => (
                <ServiceToggle
                  icon={<FileText size={18} />}
                  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: af, fieldState }) => (
                        <TextInput
                          {...af}
                          mt="sm"
                          placeholder="Customs clearing agent *"
                          error={fieldState.error?.message}
                          radius={10}
                          styles={fieldStyles}
                        />
                      )}
                    />
                  )}
                </ServiceToggle>
              )}
            />
          )}
        </Stack>
      )}
    </StepCard>
  );
}

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>
  );
}
