"use client";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { useSettings } from "@/stores/settings";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import AlertWarning from "../shared/AlertWarning";
import FallbackImage from "../shared/FallbackImage";
import Loading from "../shared/Loading";
import PersonalDetailsForm from "./PersonalDetailsForm";

export default function PaymentMethods({ payments }) {
  const [selectedPayment, setSelectedPayment] = useState(null);
  const locale = useLocale();
  const t = useTranslations("checkout-info");
  const { settings } = useSettings();
  const [orderAccept, setOrderAccept] = useState(null);

  useEffect(() => {
    setOrderAccept(settings?.site_settings?.order_accept);
    if (selectedPayment) {
      localStorage.setItem("payment_method", selectedPayment);
    }
  }, [selectedPayment, settings?.site_settings?.order_accept]);

  return (
    <>
      {!settings ? (
        <Loading />
      ) : orderAccept == 0 ? (
        <AlertWarning text={t("order-disabled")} />
      ) : (
        payments.length > 0 && (
          <section>
            <h1 className="text-xl mb-6 font-bold">{t("payment-method")}</h1>
            <RadioGroup
              onValueChange={(value) => setSelectedPayment(value)}
              value={selectedPayment}
              className="grid grid-cols-2 lg:grid-cols-4 gap-4 items-center border bg-white"
              dir={locale === "en" ? "ltr" : "rtl"}
            >
              {payments.map((payment, index) => {
                return (
                  <div
                    key={index}
                    className="flex flex-col items-center justify-start gap-3 py-6 lg:py-12 border-e cursor-pointer min-h-[200px]" // Set a minimum height
                  >
                    <FallbackImage
                      src={payment.image}
                      alt={payment.name}
                      width={40}
                      height={40}
                    />
                    <p className="font-bold text-xs lg:text-sm text-center flex-1">
                      {payment.name}
                    </p>{" "}
                    {/* Flex 1 to balance content */}
                    <RadioGroupItem
                      onClick={() => {
                        setSelectedPayment(payment.id);
                      }}
                      className="size-6"
                      value={payment.id}
                    />
                  </div>
                );
              })}
            </RadioGroup>
          </section>
        )
      )}
      {selectedPayment && <PersonalDetailsForm paymentId={selectedPayment} />}
    </>
  );
}
