import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { useTranslation } from "react-i18next";
import { useCheckout } from "@/context/helpers/checkout/CheckoutContext";
import { useEffect, useMemo, useRef } from "react";

export default function Shipping() {
  const { t, i18n } = useTranslation("checkout");
  const isArabic = i18n.language === "ar";
  const {
    shippingMethods,
    selectedShippingMethod,
    setSelectedShippingMethod,
    isLoadingShippingMethods,
  } = useCheckout();

  const autoSelectedRef = useRef(false);
  const prevShippingMethodsRef = useRef([]);

  // Set default shipping method if available
  useEffect(() => {
    // Check if shipping methods array changed (new methods fetched)
    const methodsChanged =
      JSON.stringify(shippingMethods) !==
      JSON.stringify(prevShippingMethodsRef.current);

    if (methodsChanged) {
      prevShippingMethodsRef.current = shippingMethods || [];
      // Reset auto-selection ref when new methods are loaded
      autoSelectedRef.current = false;
    }

    // Auto-select first method if available and none selected
    if (
      shippingMethods &&
      shippingMethods.length > 0 &&
      !selectedShippingMethod &&
      !autoSelectedRef.current
    ) {
      autoSelectedRef.current = true;
      // Handle both structures: nested methods property or direct method object
      const firstShipping = shippingMethods[0];
      const method = firstShipping.methods || firstShipping;
      setSelectedShippingMethod(method);
    } else if (selectedShippingMethod) {
      // Mark as selected if a method is already set
      autoSelectedRef.current = true;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shippingMethods, selectedShippingMethod]);

  const handleShippingChange = (value) => {
    const shipping = shippingMethods?.find((shipping) => {
      const method = shipping.methods || shipping;
      return method?.code === value;
    });
    if (shipping) {
      // Handle both structures: nested methods property or direct method object
      const method = shipping.methods || shipping;
      setSelectedShippingMethod(method);
    }
  };

  // Get stable value for RadioGroup - must be before any conditional returns
  const shippingValue = useMemo(() => {
    if (selectedShippingMethod?.code) return selectedShippingMethod.code;
    // Handle both structures: nested methods property or direct method object
    if (shippingMethods?.[0]) {
      const firstMethod = shippingMethods[0].methods || shippingMethods[0];
      if (firstMethod?.code) return firstMethod.code;
    }
    return "";
  }, [selectedShippingMethod?.code, shippingMethods]);

  if (isLoadingShippingMethods) {
    return (
      <div className="text-sm text-gray-500 dark:text-gray-400 mb-2">
        {t("shipping.loading", "Loading shipping methods...")}
      </div>
    );
  }

  if (!shippingMethods || shippingMethods.length === 0) {
    return (
      <div className="text-sm text-gray-500 dark:text-gray-400 mb-2">
        {t("shipping.noMethods")}
      </div>
    );
  }

  return (
    <div className="flex flex-col mb-2">
      <h5 className="mb-2 font-semibold">
        {t("summary.shipping.title", "Shipping")}
      </h5>
      <RadioGroup value={shippingValue} onValueChange={handleShippingChange}>
        {shippingMethods.map((shipping, index) => {
          // Handle both structures: nested methods property or direct method object
          const method = shipping.methods || shipping;
          if (!method) return null;

          const methodCode = method.code;
          const methodLabel =
            method.label || method.title || method.code || method.name;
          const methodPrice = method.formattedPrice || method.price;

          return (
            <div
              key={methodCode || index}
              className={`flex items-center gap-3 mb-2 ${
                isArabic ? "flex-row-reverse" : ""
              }`}
            >
              <RadioGroupItem
                value={methodCode}
                id={`shipping-${methodCode || index}`}
                className="cursor-pointer"
              />
              <Label
                className="text-sm text-thirdColor dark:text-gray-400 cursor-pointer flex-1"
                htmlFor={`shipping-${methodCode || index}`}
              >
                <div className="flex items-center justify-between">
                  <span>{methodLabel}</span>
                  {methodPrice && (
                    <span className="font-semibold ml-2">{methodPrice}</span>
                  )}
                </div>
              </Label>
            </div>
          );
        })}
      </RadioGroup>
    </div>
  );
}
