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 Payment() {
  const { t, i18n } = useTranslation("checkout");
  const isArabic = i18n.language === "ar";
  const { billingMethods, selectedPaymentMethod, setSelectedPaymentMethod } =
    useCheckout();
  const autoSelectedRef = useRef(false);

  // Set default payment method if available
  useEffect(() => {
    if (
      billingMethods &&
      billingMethods.length > 0 &&
      !selectedPaymentMethod &&
      !autoSelectedRef.current
    ) {
      autoSelectedRef.current = true;
      setSelectedPaymentMethod(billingMethods[0]);
    } else if (selectedPaymentMethod) {
      // Mark as selected if a method is already set
      autoSelectedRef.current = true;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [billingMethods, selectedPaymentMethod]);

  // Get stable value for RadioGroup - must be before any conditional returns
  const paymentValue = useMemo(() => {
    if (selectedPaymentMethod?.code) return selectedPaymentMethod.code;
    if (selectedPaymentMethod?.id) return String(selectedPaymentMethod.id);
    if (billingMethods?.[0]?.code) return billingMethods[0].code;
    if (billingMethods?.[0]?.id) return String(billingMethods[0].id);
    return "";
  }, [selectedPaymentMethod, billingMethods]);

  const handlePaymentChange = (value) => {
    const method = billingMethods?.find(
      (method) => method.code === value || method.id === value
    );
    if (method) {
      setSelectedPaymentMethod(method);
    }
  };

  if (!billingMethods || billingMethods.length === 0) {
    return (
      <div className="text-sm text-gray-500">
        {t("payment.loading", "Loading payment methods...")}
      </div>
    );
  }

  return (
    <fieldset className="space-y-4">
      <legend className="sr-only">{t("payment.legend")}</legend>
      <RadioGroup value={paymentValue} onValueChange={handlePaymentChange}>
        {billingMethods.map((method, index) => (
          <section
            key={method.id || method.code || index}
            className={`flex items-center gap-3 ${
              isArabic ? "flex-row-reverse" : ""
            }`}
          >
            <RadioGroupItem
              value={method.code || method.id}
              id={`payment-${method.id || method.code || index}`}
              className="cursor-pointer"
            />
            <Label
              className="text-sm text-thirdColor cursor-pointer"
              htmlFor={`payment-${method.id || method.code || index}`}
            >
              {method.title || method.name || method.code}
            </Label>
          </section>
        ))}
      </RadioGroup>
    </fieldset>
  );
}
