import { useEffect, useRef } from "react";
import { Controller, type UseFormReturn } from "react-hook-form";
import { FileText, Package, Train, Truck } from "lucide-react";
import { Badge, Field, FieldError, Input, Switch } from "@edr/ui-common";
import { BookingFormInputValues, type BookingFormValues } from "./schema";
import { OptionCard, OptionFieldError, StepHeader } from "./shared";

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

export function Step2ServiceType({ form }: { form: BookingForm }) {
  const serviceType = form.watch("serviceType");
  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 (serviceType === "rail") {
      form.setValue(
        "firstMile",
        { enabled: false, pickUpAddress: "" },
        { shouldDirty: true, shouldValidate: true },
      );
      form.setValue(
        "lastMile",
        { enabled: false, deliveryAddress: "" },
        { shouldDirty: true, shouldValidate: true },
      );
      form.setValue("equipmentReturn", "with_return", {
        shouldDirty: true,
      });
      form.setValue("customsClearingEnabled", false, {
        shouldDirty: true,
      });
    } else if (serviceType === "rail_forwarding") {
      form.setValue(
        "firstMile",
        {
          enabled: false,
          pickUpAddress: "",
        },
        {
          shouldDirty: false,
          shouldValidate: false,
        },
      );
      form.setValue(
        "lastMile",
        {
          enabled: false,
          deliveryAddress: "",
        },
        {
          shouldDirty: false,
          shouldValidate: false,
        },
      );
    }
  }, [serviceType, form]);

  const showServiceSections = serviceType === "rail_forwarding";

  return (
    <div className="space-y-6">
      <StepHeader
        title="Service Type"
        description="Select the service combination and configure trucking options."
      />

      <Controller
        name="serviceType"
        control={form.control}
        render={({ field, fieldState }) => (
          <Field data-invalid={fieldState.invalid}>
            <div className="grid gap-3 md:grid-cols-2">
              <OptionCard
                selected={serviceType === "rail"}
                onClick={() => field.onChange("rail")}
              >
                <div className="mb-2 flex h-9 w-9 items-center justify-center rounded-lg bg-indigo-100">
                  <Train className="h-4 w-4 text-indigo-600" />
                </div>
                <p className="font-semibold">Rail Transport Only</p>
                <p className="mt-0.5 text-xs text-muted-foreground">
                  Rail transport along the EDR corridor, with optional
                  first/last mile trucking.
                </p>
                <Badge className="mt-2 bg-indigo-100 text-indigo-700 hover:bg-indigo-100">
                  Option A
                </Badge>
              </OptionCard>

              <OptionCard
                selected={serviceType === "rail_forwarding"}
                onClick={() => field.onChange("rail_forwarding")}
              >
                <div className="mb-2 flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
                  <Package className="h-4 w-4 text-primary" />
                </div>
                <p className="font-semibold">Logistics</p>
                <p className="mt-0.5 text-xs text-muted-foreground">
                  Rail transport plus documentation, customs liaison, and a
                  dedicated coordinator.
                </p>
                <Badge className="mt-2 bg-emerald-100 text-emerald-700 hover:bg-emerald-100">
                  Option B
                </Badge>
              </OptionCard>
            </div>
            <OptionFieldError error={fieldState.error} />
          </Field>
        )}
      />

      {showServiceSections && (
        <div className="divide-y divide-border rounded-xl border border-border">
          <div className="p-4">
            <Controller
              name="firstMile.enabled"
              control={form.control}
              render={({ field }) => (
                <div className="flex items-start justify-between gap-4">
                  <div className="flex items-start gap-3">
                    <Truck className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium">
                        First Mile - Pick-up
                      </p>
                      <p className="mt-0.5 text-xs text-muted-foreground">
                        Truck pick-up from your premises (Door to Port) to the
                        origin rail yard.
                      </p>
                    </div>
                  </div>
                  <Switch
                    checked={field.value}
                    onCheckedChange={(value) => {
                      field.onChange(value);
                      if (!value) {
                        form.setValue("firstMile.pickUpAddress", "", {
                          shouldDirty: true,
                          shouldValidate: true,
                        });
                      }
                    }}
                  />
                </div>
              )}
            />
            {firstMileEnabled && (
              <Controller
                name="firstMile.pickUpAddress"
                control={form.control}
                render={({ field, fieldState }) => (
                  <Field className="mt-3" data-invalid={fieldState.invalid}>
                    <Input
                      {...field}
                      aria-invalid={fieldState.invalid}
                      placeholder="Pick-up address *"
                    />
                    <FieldError errors={[fieldState.error]} />
                  </Field>
                )}
              />
            )}
          </div>

          <div className="p-4">
            <Controller
              name="lastMile.enabled"
              control={form.control}
              render={({ field }) => (
                <div className="flex items-start justify-between gap-4">
                  <div className="flex items-start gap-3">
                    <Truck className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium">
                        Last Mile - Delivery
                      </p>
                      <p className="mt-0.5 text-xs text-muted-foreground">
                        Truck delivery from the destination rail yard to the
                        final address (Port to Door).
                      </p>
                    </div>
                  </div>
                  <Switch
                    checked={field.value}
                    onCheckedChange={(value) => {
                      field.onChange(value);
                      if (!value) {
                        form.setValue("lastMile.deliveryAddress", "", {
                          shouldDirty: true,
                          shouldValidate: true,
                        });
                        form.setValue("equipmentReturn", "with_return", {
                          shouldDirty: true,
                        });
                      }
                    }}
                  />
                </div>
              )}
            />
            {lastMileEnabled && (
              <Controller
                name="lastMile.deliveryAddress"
                control={form.control}
                render={({ field, fieldState }) => (
                  <Field className="mt-3" data-invalid={fieldState.invalid}>
                    <Input
                      {...field}
                      aria-invalid={fieldState.invalid}
                      placeholder="Delivery address *"
                    />
                    <FieldError errors={[fieldState.error]} />
                  </Field>
                )}
              />
            )}
          </div>

          {lastMileEnabled && (
            <div className="p-4">
              <Controller
                name="equipmentReturn"
                control={form.control}
                render={({ field }) => (
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex items-start gap-3">
                      <div>
                        <p className="text-sm font-medium">Equipment Return</p>
                        <p className="mt-0.5 text-xs text-muted-foreground">
                          {field.value === "with_return"
                            ? "Container returned to EDR after unloading."
                            : "Container retained by the customer after delivery."}
                        </p>
                      </div>
                    </div>
                    <Switch
                      checked={field.value === "with_return"}
                      onCheckedChange={(value) => {
                        field.onChange(
                          value ? "with_return" : "without_return",
                        );
                      }}
                    />
                  </div>
                )}
              />
            </div>
          )}

          <div className="p-4">
            <Controller
              name="customsClearingEnabled"
              control={form.control}
              render={({ field }) => (
                <div className="flex items-start justify-between gap-4">
                  <div className="flex items-start gap-3">
                    <FileText className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium">
                        Customs Clearing Service
                      </p>
                      <p className="mt-0.5 text-xs text-muted-foreground">
                        EDR handles customs documentation and clearance on your
                        behalf.
                      </p>
                    </div>
                  </div>
                  <Switch
                    checked={field.value}
                    onCheckedChange={field.onChange}
                  />
                </div>
              )}
            />
          </div>
        </div>
      )}
    </div>
  );
}
