import { useEffect, useMemo } from "react";
import { Controller, type UseFormReturn } from "react-hook-form";
import { Flame, MapPin, Snowflake } from "lucide-react";
import { Field, SelectItem, Separator, Skeleton, Switch } from "@edr/ui-common";
import type { Freight } from "@edr/types";
import {
  BookingFormInputValues,
  type BookingFormValues,
  getRouteDirection,
} from "./schema";
import { SelectField, StepHeader, StepLabel } from "./shared";

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

export function Step4Route({
  form,
  referenceData,
  isLoading,
}: {
  form: BookingForm;
  referenceData?: Freight.BookingReferenceData;
  isLoading?: boolean;
}) {
  const originYard = form.watch("originYard");
  const destinationYard = form.watch("destinationYard");

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

  const shippingLineOptions = useMemo(() => {
    if (!referenceData?.shipping_line) return [];
    return referenceData.shipping_line.map((sl) => ({
      value: sl.name,
      label: sl.name,
    }));
  }, [referenceData]);

  const direction = getRouteDirection(originYard, destinationYard);
  const directionStyle: Record<string, string> = {
    export: "bg-sky-50 text-sky-800 border-sky-200",
    import: "bg-amber-50 text-amber-800 border-amber-200",
    domestic: "bg-muted text-muted-foreground border-border",
  };
  const directionLabel: Record<string, string> = {
    export: "Export workflow (inside country to outside country)",
    import: "Import workflow (outside country to inside country)",
    domestic: "Domestic corridor",
  };

  useEffect(() => {
    if (direction === "domestic") {
      form.setValue("shippingLine", "", { shouldDirty: true });
    }
  }, [direction]);

  const stationSelectDisabled = yardOptions.length === 0;

  return (
    <div className="space-y-6">
      <StepHeader
        title="Route"
        description="Select the origin and destination yards."
      />

      {isLoading ? (
        <LoadingSkeleton />
      ) : (
        <div className="space-y-3">
          <StepLabel>Route</StepLabel>
          <div className="grid gap-3 sm:grid-cols-2">
            <Controller
              name="originYard"
              control={form.control}
              render={({ field, fieldState }) => (
                <SelectField
                  field={field}
                  error={fieldState.error}
                  label="Origin Yard*"
                  placeholder="Select origin..."
                  disabled={stationSelectDisabled}
                >
                  <YardSelectOptions
                    options={yardOptions}
                    excludeValue={destinationYard}
                  />
                </SelectField>
              )}
            />
            <Controller
              name="destinationYard"
              control={form.control}
              render={({ field, fieldState }) => (
                <SelectField
                  field={field}
                  error={fieldState.error}
                  label="Destination Yard *"
                  placeholder="Select destination..."
                  disabled={stationSelectDisabled}
                >
                  <YardSelectOptions
                    options={yardOptions}
                    excludeValue={originYard}
                  />
                </SelectField>
              )}
            />
          </div>
          {direction && (
            <div
              className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-xs font-medium ${directionStyle[direction]}`}
            >
              <MapPin className="h-3.5 w-3.5 shrink-0" />
              {directionLabel[direction]}
            </div>
          )}
        </div>
      )}

      {direction && direction != "domestic" && (
        <Controller
          name="shippingLine"
          control={form.control}
          render={({ field, fieldState }) => (
            <SelectField
              field={field}
              error={fieldState.error}
              label="Shipping Line"
              placeholder="Select shipping line..."
            >
              {shippingLineOptions.map((sl) => (
                <SelectItem key={sl.value} value={sl.value}>
                  {sl.label}
                </SelectItem>
              ))}
            </SelectField>
          )}
        />
      )}
      <Separator />

      <div className="space-y-0 divide-y divide-border">
        <Controller
          name="isHazardous"
          control={form.control}
          render={({ field }) => (
            <div className="flex items-center justify-between py-3">
              <div className="flex items-center gap-3">
                <Flame className="h-4 w-4 shrink-0 text-red-500" />
                <div>
                  <p className="text-sm font-medium">Hazardous Material</p>
                  <p className="text-xs text-muted-foreground">
                    Applies a Hazard Surcharge to the final bill.
                  </p>
                </div>
              </div>
              <Switch checked={field.value} onCheckedChange={field.onChange} />
            </div>
          )}
        />
        <Controller
          name="isRefrigerated"
          control={form.control}
          render={({ field }) => (
            <div className="flex items-center justify-between py-3">
              <div className="flex items-center gap-3">
                <Snowflake className="h-4 w-4 shrink-0 text-sky-500" />
                <div>
                  <p className="text-sm font-medium">Refrigerated Cargo</p>
                  <p className="text-xs text-muted-foreground">
                    Temperature-controlled transport applies a Refrigerator
                    Surcharge.
                  </p>
                </div>
              </div>
              <Switch checked={field.value} onCheckedChange={field.onChange} />
            </div>
          )}
        />
      </div>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="space-y-4 rounded-xl border border-border p-4">
      <div className="grid gap-3 sm:grid-cols-2">
        <div className="space-y-2">
          <Skeleton className="h-3 w-20" />
          <Skeleton className="h-10 w-full" />
        </div>
        <div className="space-y-2">
          <Skeleton className="h-3 w-24" />
          <Skeleton className="h-10 w-full" />
        </div>
      </div>
      <Skeleton className="h-8 w-full" />
    </div>
  );
}

function YardSelectOptions({
  options,
  excludeValue,
}: {
  options: Array<{ value: string; label: string; country: string }>;
  excludeValue: string;
}) {
  if (options.length === 0) {
    return (
      <SelectItem value="__yards_empty" disabled>
        No yards available
      </SelectItem>
    );
  }

  const availableOptions = options.filter(
    (option) => option.value !== excludeValue,
  );

  return (
    <>
      {availableOptions.map((option) => (
        <SelectItem key={option.value} value={option.value}>
          {option.label}
        </SelectItem>
      ))}
    </>
  );
}
