"use client";

import React, { useEffect, useState } from "react";
import Select from "react-select";
import Image from "next/image";
import Button from "@/components/common/Button";

import axios from "axios";
import { useRouter, useSearchParams } from "next/navigation";
import { buyNow, getMyAddresses } from "@/lib/actions/buyAction";
import { useAppSelector } from "@/app/store/hooks";
import { RootState } from "@/app/store/store";
import { checkAuthErrorGet } from "@/lib/checkAuthError";
import { toast } from "react-toastify";
import { useDispatch } from "react-redux";
import { useTranslations } from "next-intl";
import { getStoredLocale } from "@/lib/getLocale";
import { useForm, FormProvider, Controller } from "react-hook-form";
import { z } from "zod";

import Input from "@/components/common/CustomInputField";
import { getCities, getStates } from "@/lib/actions/countryStateCityActions";
import { zodResolver } from "@hookform/resolvers/zod";
import PhoneInput from "react-phone-input-2";
import { useSelectTheme } from "@/hooks/useSelectTheme";
import {
  AttributeKeys,
  OtherAttribute,
  VehicleNumber,
} from "../../../../types/common-types";
import {
  getImageUrl,
  getMobileNumberSmallImageUrl,
  getVehiclePlateSmallImageUrl,
  resolveOtherAttributeSmallImage,
  transparentClass,
} from "@/hooks/useImageUrl";
import { getExpiryYears } from "@/lib/utils/getExpiryYears";

const getPaymentSchema = (t: any) =>
  z.object({
    paymentMethod: z.string().min(1, t("validation.payment_method_required")),
    cardholderName: z.string().min(1, t("validation.cardholder_name_required")),
    cardNumber: z
      .string()
      .min(1, t("validation.card_number_required"))
      .transform((val) => val.replace(/\s/g, ""))
      .refine((val) => /^\d{16,}$/.test(val), {
        message: t("validation.card_number_invalid"),
      }),
    expiryMonth: z
      .string()
      .min(1, t("validation.expiry_month_required"))
      .refine(
        (val) => {
          const num = Number(val);
          return num >= 1 && num <= 12;
        },
        { message: t("validation.expiry_month_invalid") }
      ),
    expiryYear: z.string().min(1, t("validation.expiry_year_required")),
    cvc: z
      .string()
      .min(3, t("validation.cvc_required"))
      .max(4, t("validation.cvc_max_length"))
      .regex(/^\d+$/, t("validation.cvc_numeric")),
  });

const getAddressSchema = (t: any) =>
  z.object({
    short_address: z
      .string()
      .min(1, t("validation.short_address_required"))
      .max(8, t("validation.short_address_max_length")),
    building_name: z
      .string()
      .min(1, t("validation.building_name_required"))
      .max(6, t("validation.building_name_max_length")),
    street: z.string().min(1, t("validation.street_required")),
    secondary_number: z
      .string()
      .min(1, t("validation.secondary_number_required"))
      .max(6, t("validation.secondary_number_max_length")),
    district: z.string().min(1, t("validation.district_required")),
    address_line_1: z.string().min(1, t("validation.address_line_1_required")),
    address_line_2: z.string().optional(),
    state: z.object({
      value: z.union([z.number(), z.string()]),
      label: z.string()
    })
      .nullable()
      .refine((val) => val && val.value !== "" && val.value !== 0, {
        message: t("validation.state_required"),
      }),

    city: z
      .object({
        value: z.union([z.number(), z.string()]),
        label: z.string()
      })
      .nullable()
      .refine((val) => val && val.value !== "" && val.value !== 0, {
        message: t("validation.city_required"),
      }),
    postal_code: z
      .string()
      .min(1, t("validation.postal_code_required"))
      .min(3, t("validation.postal_code_min_length"))
      .max(6, t("validation.postal_code_max_length")),
    contact_number: z
      .string()
      .min(1, t("validation.phone_numben_required"))
      .regex(/^[+]?[0-9]{8,15}$/, t("validation.valid_phone")),
    isPrimary: z.boolean().default(false).optional(),
  });

type AddressFormValues = z.infer<ReturnType<typeof getAddressSchema>>;
type PaymentFormValues = z.infer<ReturnType<typeof getPaymentSchema>>;

export default function Checkout() {
  const router = useRouter();
  const { user } = useAppSelector((state: RootState) => state.auth);
  const dispatch = useDispatch();
  const t = useTranslations();
  const locale = getStoredLocale();
  const [product, setProduct] = useState<any>(null);
  const searchParams = useSearchParams();
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [countryCode, setCountryCode] = useState<string>("");
  const [states, setStates] = useState<any>(null);
  const [cities, setCities] = useState<any>(null);
  const [addresses, setAllAddresses] = useState<any>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [selectedAddressId, setSelectedAddressId] = useState<string>("");

  const [productType, setProductType] = useState<"product" | AttributeKeys>(
    "product"
  );

  const addressSchema = getAddressSchema(t);
  const paymentSchema = getPaymentSchema(t);

  const [otherAttribute, setOtherAttribute] = useState<
    | OtherAttribute<"mobile_number">
    | OtherAttribute<"vehicle_number_plate">
    | null
  >(null);

  const getStateDate = async (country_id: any) => {
    var isStateData = [];
    setCities([]);
    try {
      const response = await getStates(user?.token, country_id);
      if (response.success && Array.isArray(response?.stateData)) {
        isStateData = response?.stateData.map((opt: any) => ({
          value: opt._id,
          label: opt.name,
        }));
      }
    } catch (error: any) {
      if (checkAuthErrorGet(error, dispatch, router)) return;
      // toast.error(error?.response?.data?.message || t("validation.error_msg"));
    } finally {
      setStates(isStateData);
    }
  };
  const getCityDate = async (state_id: any) => {
    var isCityData = [];
    try {
      const response = await getCities(user?.token, state_id);
      if (response.success && Array.isArray(response?.cityData)) {
        isCityData = response?.cityData.map((opt: any) => ({
          value: opt._id,
          label: opt.name,
        }));
      }
    } catch (error: any) {
      if (checkAuthErrorGet(error, dispatch, router)) return;
      // toast.error(error?.response?.data?.message || t("validation.error_msg"));
    } finally {
      setCities(isCityData);
    }
  };

  useEffect(() => {
    if (!searchParams || !user?.token) {
      return;
    }

    const handleBuyNow = async () => {
      try {
        setIsLoading(true);
        const response = await buyNow(user?.token, {
          chatId: searchParams!.get("chatId") as string,
          conversationId: searchParams!.get("conversationId") as string,
          productId: searchParams!.get("productId") as string,
          sender: searchParams!.get("sender") as string,
        });

        if (response.success) {
          const data = response.data?.product;

          let obj: any = {};
          data.forEach((attr: any) => {
            if (attr.type === "text" && attr.slug === "title") {
              (obj as any).title = attr.value?.content;
            }

            if (attr.type.includes("singleimageuploader")) {
              const files = attr.value?.meta?.files;
              if (files && files.length > 0 && files[0].location) {
                (obj as any).image = files[0].location;
              }
            }

            // if (attr.slug.includes("price")) {
            //   (obj as any).price = attr.value?.content;
            // }
          });

          let price = response.data?.chat?.offer.amount;
          (obj as any).price = price;

          const otherAttr = response.data?.product.find(
            (obj: any) => obj.slug === "other-attribute"
          );

          if (otherAttr && otherAttr?.value?.valueType === "mobile_number") {
            setOtherAttribute({
              content: otherAttr?.value?.content,
              meta: otherAttr?.value?.meta,
            } as OtherAttribute<"mobile_number">);
            setProductType(otherAttr?.value?.valueType);
          } else if (
            otherAttr &&
            otherAttr?.value?.valueType === "vehicle_number_plate"
          ) {
            setOtherAttribute({
              content: otherAttr?.value?.content,
              meta: otherAttr?.value?.meta,
            } as OtherAttribute<"vehicle_number_plate">);
            setProductType(otherAttr?.value?.valueType);
          } else {
            setOtherAttribute(null);
            setProductType("product");
          }

          setProduct([obj]);
        }
      } catch (error: any) {
        if (checkAuthErrorGet(error, dispatch, router)) return;

        const errorMsg =
          error?.response?.data?.message || t("validation.error_msg");
        toast.error(errorMsg);
        router.back();
      } finally {
        setIsLoading(false);
      }
    };

    const getAddresses = async () => {
      try {
        setIsLoading(true);

        const response = await getMyAddresses(user?.token);

        if (response.success) {
          const result = response.data.map((item: any) => {
            return {
              id: item.id,
              address_line_1: item.address_line_1,
              address_line_2: item.address_line_2,
              state: item.state
                ? { value: item.state._id || item.state.id || "", label: item.state.name || "" }
                : { value: "", label: "" },
              city: item.city
                ? { value: item.city._id || item.city.id || "", label: item.city.name || "" }
                : { value: "", label: "" },
              building_name: item.building_name,
              street: item.street,
              short_address: item.short_address,
              secondary_number: item.secondary_number,
              district: item.district,
              postal_code: item.postal_code,
              country_code: item.country_code,
              contact_number: item.country_code + item.contact_number,
              country: item.country ?? "",
              isPrimary: item.isPrimary,
            };
          });

          result.push({
            id: "new",
            address_line_1: "",
            address_line_2: "",
            state: { value: "", label: "" },
            city: { value: "", label: "" },
            building_name: "",
            street: "",
            short_address: "",
            secondary_number: "",
            district: "",
            postal_code: "",
            contact_number: "",
            country_code: "",
            country: {
              _id: process.env.NEXT_PUBLIC_COUNTRY_CODE,
              name: process.env.NEXT_PUBLIC_COUNTRY_NAME,
            },
            isPrimary: false,
          });

          setAllAddresses(result);
          const primary = result.find((addr: any) => addr.isPrimary);
          if (primary) {
            setSelectedAddressId(primary.id);
            methods.reset(primary);
          }
        }
      } catch (error: any) {
        if (checkAuthErrorGet(error, dispatch, router)) return;

        const errorMsg =
          error?.response?.data?.message || t("validation.error_msg");
        toast.error(errorMsg);
      } finally {
        setIsLoading(false);
      }
    };

    handleBuyNow();
    getAddresses();
  }, [user?.token]);

  const { customStyles } = useSelectTheme();

  const [cardNumber, setCardNumber] = useState("");
  const [cvcNumber, setCvcNumber] = useState("");
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // Remove all non-digits
    const digits = e.target.value.replace(/\D/g, "");
    // Limit to 20 digits
    const limited = digits.slice(0, 20);
    // Group into blocks of 4 with spaces
    const formatted = limited.replace(/(.{4})/g, "$1 ").trim();
    setCardNumber(formatted);
    paymentMethods.setValue("cardNumber", formatted, { shouldValidate: true });
  };

  const handleChangeCVC = (e: React.ChangeEvent<HTMLInputElement>) => {
    // Remove all non-digits
    const digits = e.target.value.replace(/\D/g, "");
    // Limit to 4 digits
    const limited = digits.slice(0, 4);
    // No formatting needed, just store the 4 digits
    setCvcNumber(limited);
    paymentMethods.setValue("cvc", limited, { shouldValidate: true });
  };

  const methods = useForm<AddressFormValues>({
    resolver: zodResolver(addressSchema),
    mode: "onChange",
    reValidateMode: "onChange",
    defaultValues: {
      short_address: "",
      building_name: "",
      street: "",
      secondary_number: "",
      district: "",
      state: { value: "", label: "" },
      city: { value: "", label: "" },
      postal_code: "",
      address_line_1: "",
      address_line_2: "",
      contact_number: "",
      isPrimary: false,
    },
  });

  const {
    handleSubmit,
    control,
    setValue,
    reset,
    formState: { errors },
  } = methods;

  useEffect(() => {
    (async function () {
      if (addresses && addresses.length > 0) {
        const primary = addresses.find((obj: any) => obj.isPrimary);

        if (primary) {
          // get state and city of primary address
          await getStateDate(primary.country._id);
          await getCityDate(primary.state.value);

          methods.reset(primary);
        } else {
          if (addresses.length == 1) {
            // new address
            await getStateDate(addresses[0].country._id);
          } else {
            await getStateDate(addresses[0].country._id);
            await getCityDate(addresses[0].state.value);
          }
          methods.reset(addresses[0]);
        }
      }
    })();
  }, [addresses]);

  //   Payment form
  const paymentMethods = useForm<PaymentFormValues>({
    resolver: zodResolver(paymentSchema),
    mode: "onChange",
    reValidateMode: "onChange",
    defaultValues: {
      paymentMethod: "",
      cardholderName: "",
      cardNumber: "",
      expiryMonth: "",
      expiryYear: "",
      cvc: "",
    },
  });

  const {
    register: registerPayment,
    handleSubmit: handlePaymentSubmit,
    watch: watchPayment,
    formState: { errors: paymentErrors },
  } = paymentMethods;

  const paymentSubmit = async () => {
    if (isProcessing) return;
    const isAddressValid = await methods.trigger();
    const isPaymentValid = await paymentMethods.trigger();

    if (!isAddressValid || !isPaymentValid) {
      const firstErrorField = document.querySelector("[aria-invalid='true']");
      if (firstErrorField) {
        firstErrorField.scrollIntoView({ behavior: "smooth", block: "center" });
      }
      return;
    }

    setIsProcessing(true);

    try {
      const paymentData = paymentMethods.getValues();
      const addressData = methods.getValues();

      (addressData as any).country_code = countryCode;

      let temp = countryCode.replace(/^\+/, "");
      const str = addressData.contact_number;
      const prefix = temp;

      let extracted = str.startsWith(prefix) ? str.slice(prefix.length) : str;

      addressData.contact_number = extracted;

      let paymentBrand =
        paymentData.paymentMethod === "mastercard"
          ? "MASTER"
          : paymentData.paymentMethod === "visa"
            ? "VISA"
            : "MADA";

      const payload = {
        address: addressData,
        otherDetails: {
          chatId: searchParams!.get("chatId") as string,
          conversationId: searchParams!.get("conversationId") as string,
          productId: searchParams!.get("productId") as string,
          sender: searchParams!.get("sender") as string,
          negotiatePrice: product[0]?.price,
        },
        payment: {
          amount: Number(product[0]?.price),
          currency: "EUR",
          paymentBrand: paymentBrand, // or brand selected by user (VISA 123, MASTER 123, MADA 742)
          card_number: paymentData.cardNumber.replaceAll(" ", ""),
          holder: paymentData.cardholderName,
          expiryMonth: paymentData.expiryMonth,
          expiryYear: paymentData.expiryYear,
          cvv: paymentData.cvc,
        },
      };
      const response = await axios.post(
        `/api/hyperpay-server-payment`,
        payload,
        {
          headers: {
            Authorization: "Bearer " + user?.token,
            "Accept-Language": locale,
          },
        }
      );
      toast.success(t("checkout.order_successful"));
      router.replace("/my-orders");

    } catch (error: any) {
      console.log({ error: "Payment error" });
      if (checkAuthErrorGet(error, dispatch, router)) return;
      const errorMsg =
        error?.response?.data?.message || t("validation.error_msg");
      toast.error(errorMsg);
    } finally {
      setIsProcessing(false);
    }
  };

  const renderProductInfo = () => {
    if (!product) return;

    switch (productType) {
      case "mobile_number": {
        const mobileAttr = otherAttribute as OtherAttribute<"mobile_number">;
        return (
          <div className="flex gap-3">
            <div className="w-52">
              <img
                className="w-full rounded-md mb-2 h-fit object-cover"
                src={`${resolveOtherAttributeSmallImage({
                  otherAttr: otherAttribute
                    ? {
                      ...otherAttribute,
                      valueType: "mobile_number",
                    }
                    : null,
                  productImage: getImageUrl(product[0]?.image),
                })}`}
                alt="Preview"
                width={93}
                height={93}
                onError={(e) => {
                  e.currentTarget.onerror = null;
                  e.currentTarget.src = "/default.jpg";
                }}
              />
            </div>
            <div className="w-[calc(100%--80px)]">
              <h4 className="text-base text-neutrals800 font-medium dark:text-gray-200 mb-1">
                {product[0]?.title}
              </h4>
              {otherAttribute && (
                <p className="text-sm text-neutrals800 font-normal dark:text-gray-200">
                  {t("mobile_number")}: {mobileAttr?.content[0].number}
                </p>
              )}
              <p className="mt-1 text-base font-bold text-primary500 dark:text-primary400">
                <strong className="font-semibold text-neutrals800 dark:text-gray-200">
                  {t("checkout.price")}:
                </strong>{" "}
                SAR {product[0]?.price}
              </p>
            </div>
          </div>
        );
      }

      default: {
        return (
          <div className="flex gap-3">
            <div className="w-52">
              <img
                className={`w-full rounded-md mb-2 h-fit object-cover ${transparentClass}`}
                src={`${resolveOtherAttributeSmallImage({
                  otherAttr: otherAttribute
                    ? {
                      ...otherAttribute,
                      valueType: "vehicle_number_plate",
                    }
                    : null,
                  productImage: getImageUrl(product[0]?.image),
                })}`}
                alt="Preview"
                width={93}
                height={93}
                onError={(e) => {
                  e.currentTarget.onerror = null;
                  e.currentTarget.src = "/default.jpg";
                }}
              />
            </div>
            <div className="w-[calc(100%--80px)]">
              <h4 className="text-base text-neutrals800 font-medium dark:text-gray-200 mb-1">
                {product[0]?.title}
              </h4>
              <p className="mt-1 text-base font-bold text-primary500 dark:text-primary400">
                <strong className="font-semibold text-neutrals800 dark:text-gray-200">
                  {t("checkout.price")}:
                </strong>{" "}
                SAR {product[0]?.price}
              </p>
            </div>
          </div>
        );
      }
    }
  };

  if (isLoading) {
    return <div>{t("checkout.loading")}</div>;
  }

  return (
    <>
      <section className="p-6">
        <div className="max-w-w1660 mx-auto relative">
          <div className="grid-wrap flex gap-5 max-md:flex-col-reverse max-md:flex-wrap">
            <div className="w-[70%] p-6 bg-gray-50 rounded-md dark:bg-darkbg max-lg:w-[50%] max-xl:w-[60%] max-md:w-full max-md:p-4">
              <h2 className="text-xl font-bold text-neutrals800 pb-5 dark:text-gray-200">
                {t("checkout.billing_details")}
              </h2>

              <div className="flex items-center gap-3 flex-wrap mb-5 max-md:gap-2">
                {addresses &&
                  addresses?.map((ele: any, index: number) => {
                    const isNewAddress = index === addresses.length - 1;
                    const isSelected = selectedAddressId === ele.id;
                    return (
                      <label
                        className="flex items-center cursor-pointer max-w-full"
                        key={ele.id || index}
                        // onClick={() => {
                        //   if (index != addresses.length - 1) {
                        //     // getStateDate(addresses[index].country._id);

                        //     getCityDate(addresses[index].state.value);
                        //   }
                        onClick={() => {
                          if (!isNewAddress && ele.state?.value) {
                            getCityDate(ele.state.value);
                          }
                          setSelectedAddressId(ele.id);
                          // methods.reset(addresses[index]);
                          methods.reset(ele);
                        }}
                      >
                        <input
                          type="radio"
                          name="mainCategory"
                          value={ele.id}
                          className="peer hidden"
                          checked={isSelected}
                          onChange={() => setSelectedAddressId(ele.id)}
                        />
                        <div
                          className={`w-full flex items-center gap-2.5 border px-3 py-2 rounded-lg transition-colors 
                ${isSelected
                              ? "bg-primary500 text-white border-primary500"
                              : "border-neutrals100 dark:border-darkborder text-black dark:text-white"
                            }`}
                        >
                          <div className="w-full">
                            <span className="text-sm font-medium">
                              {isNewAddress
                                ? t("checkout.new_address")
                                : `${t("checkout.address")} ${index + 1}`}
                            </span>
                          </div>
                        </div>
                      </label>
                    );
                  })}
              </div>

              {/* Address Form */}
              {addresses && (
                <FormProvider {...methods}>
                  <form>
                    <div className="address-details grid grid-cols-2 col-span-2 gap-4 max-[991px]:grid-cols-1 max-[991px]:col-span-1 max-[767px]:col-span-2 max-[767px]:grid-cols-2">
                      <Input
                        label={t("my_address.short_address")}
                        name="short_address"
                        placeholder={t("my_address.short_address_placeholder")}
                        required
                      />
                      <Input
                        label={t("my_address.building_name")}
                        name="building_name"
                        type="number"
                        placeholder={t("my_address.building_name_placeholder")}
                        required
                      />
                      <Input
                        label={t("my_address.street")}
                        name="street"
                        placeholder={t("my_address.street_placeholder")}
                        required
                      />
                      <Input
                        label={t("my_address.secondary_number")}
                        name="secondary_number"
                        type="number"
                        placeholder={t(
                          "my_address.secondary_number_placeholder"
                        )}
                        required
                      />
                      <Input
                        label={t("my_address.district")}
                        name="district"
                        placeholder={t("my_address.district_placeholder")}
                        required
                      />

                      <div>
                        <label
                          htmlFor="state"
                          className="block text-sm font-medium text-neutrals800 mb-1 dark:text-neutrals400"
                        >
                          {t("my_address.state")}{" "}
                          <span className="text-sm text-red-500">*</span>
                        </label>
                        <Controller
                          name="state"
                          control={control}
                          render={({ field }) => (
                            <Select
                              {...field}
                              inputId="state"
                              options={states}
                              placeholder={t("my_address.select_state")}
                              className="react-select-container"
                              classNamePrefix="react-select"
                              styles={customStyles}
                              // key={themeKey}
                              // isLoading={isLoadingStates}
                              loadingMessage={() => t("common.loading")}
                              noOptionsMessage={() => t("common.no_options")}
                              value={
                                states?.find(
                                  (option: any) =>
                                    option?.value === field?.value?.value
                                ) || null
                              }
                              onChange={(val: any) => {
                                field.onChange(val);
                                // setCities(null);
                                getCityDate(val?.value);
                              }}
                              isClearable
                            />
                          )}
                        />
                        {methods.formState.errors.state && (
                          <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                            {(methods.formState.errors.state as any)?.value?.message ||
                              (methods.formState.errors.state as any)?.message}
                          </p>
                        )}
                      </div>

                      <div>
                        <label
                          htmlFor="city"
                          className="block text-sm font-medium text-neutrals800 mb-1 dark:text-neutrals400"
                        >
                          {t("my_address.city")}{" "}
                          <span className="text-sm text-red-500">*</span>
                        </label>
                        <Controller
                          name="city"
                          control={control}
                          render={({ field }) => (
                            <Select
                              {...field}
                              inputId="city"
                              options={cities}
                              placeholder={t("my_address.select_city")}
                              className="react-select-container"
                              classNamePrefix="react-select"
                              styles={customStyles}
                              // key={themeKey}
                              // isLoading={isLoadingCities}
                              loadingMessage={() => t("common.loading")}
                              noOptionsMessage={() => t("common.no_options")}
                              value={
                                cities?.find(
                                  (option: any) =>
                                    option.value === field.value?.value
                                ) || null
                              }
                              onChange={(val: any) => {
                                field.onChange(val);
                              }}
                              // isDisabled={
                              //   !selectedState?.value || isLoadingCities
                              // }
                              isClearable
                            />
                          )}
                        />
                        {methods.formState.errors.city && (
                          <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                            {(methods.formState.errors.city as any)?.value?.message ||
                              (methods.formState.errors.city as any)?.message}
                          </p>
                        )}
                      </div>

                      <Input
                        label={t("my_address.postal_code")}
                        type="number"
                        name="postal_code"
                        placeholder={t("my_address.postal_code_placeholder")}
                        required
                      />
                      <Input
                        label={t("my_address.address_line_1")}
                        name="address_line_1"
                        placeholder={t("my_address.address_line_1_placeholder")}
                        required
                      />
                      <Input
                        label={t("my_address.address_line_2")}
                        name="address_line_2"
                        placeholder={t("my_address.address_line_2_placeholder")}
                      />

                      <div>
                        <label
                          htmlFor="city"
                          className="block text-sm font-medium text-neutrals800 mb-1 dark:text-neutrals400"
                        >
                          {t("my_address.contact_number")}{" "}
                          <span className="text-sm text-red-500">*</span>
                        </label>
                        <Controller
                          name="contact_number"
                          control={control}
                          // rules={validationRules}
                          defaultValue=""
                          render={({ field, fieldState: { error } }) => (
                            <>
                              <PhoneInput
                                country="sa"
                                value={field.value}
                                placeholder={t(
                                  "my_address.contact_number_placeholder"
                                )}
                                onChange={(value: string, country: any) => {
                                  field.onChange(value);
                                  const countryCode: string =
                                    "+" + country.dialCode;
                                  setCountryCode(countryCode);
                                }}
                                enableSearch
                                inputProps={{
                                  name: "phone",
                                }}
                                containerClass="relative w-full rounded-lg bg-white text-neutrals400 leading-5 px-2 py-1 pe-9 country-number-drop border border-neutrals100 dark:bg-background dark:border dark:border-darkborder"
                                inputClass={`!w-full !pl-10 !pr-4 !py-3 !text-base !text-gray-500 !rounded-lg !border-none focus:!outline-none ${error ? "!border-red-500" : ""
                                  }`}
                                buttonClass="!absolute !left-1 !top-1/2 !-translate-y-1/2 !bg-white !border-none !p-0 !m-0 !z-10"
                                dropdownClass="!z-50 !bg-white !shadow-lg !rounded-md !text-sm max-h-60 overflow-y-auto"
                                searchPlaceholder="Search..."
                              />
                            </>
                          )}
                        />
                        {methods.formState.errors.contact_number && (
                          <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                            {methods.formState.errors.contact_number.message}
                          </p>
                        )}
                      </div>

                      {/* <Input
                        label={t("my_address.contact_number")}
                        type="country_code_phone"
                        name="contact_number"
                        placeholder={t("my_address.contact_number_placeholder")}
                        setCountryCode={setAddressCountryCode}
                        required
                      /> */}
                    </div>
                  </form>
                </FormProvider>
              )}
            </div>
            <div className="w-[30%] p-6 bg-gray-50 rounded-md dark:bg-darkbg h-fit max-lg:w-[50%] max-xl:w-[40%] max-md:w-full max-md:p-4">
              <h2 className="text-xl font-bold text-neutrals800 pb-5 dark:text-gray-200">
                {t("checkout.product_details")}
              </h2>

              <div className="product-details">
                {renderProductInfo()}
                <form>
                  <div className="mt-4 space-y-3">
                    <div className="select-payment-gatway flex gap-1 flex-wrap gap-y-3 mb-4">
                      <Controller
                        name="paymentMethod"
                        control={paymentMethods.control}
                        rules={{ required: "Payment Method is required" }}
                        render={({ field }) => (
                          <>
                            {[
                              {
                                value: "mada",
                                label: t("checkout.payment_options.mada"),
                                logo: "/Mada_Logo.png",
                                classes: "max-w-[62px] m-auto mb-2 h-fit",
                              },
                              {
                                value: "sadad",
                                label: t("checkout.payment_options.sadad"),
                                logo: "/sadad_logo.png",
                                classes: "max-w-[62px] m-auto mb-2 h-fit",
                              },
                              {
                                value: "mastercard",
                                label: t("checkout.payment_options.mastercard"),
                                logo: "/master_logo.png",
                                classes: "max-w-[40px] m-auto mb-2 h-fit",
                              },
                            ].map((method) => (
                              <label
                                key={method.value}
                                className="flex items-center cursor-pointer max-w-full"
                              >
                                <input
                                  type="radio"
                                  value={method.value}
                                  checked={field.value === method.value}
                                  onChange={() => field.onChange(method.value)}
                                  className="peer hidden"
                                />
                                <div className="w-full min-h-[85px] flex items-center gap-2.5 border-2 border-neutraks100 px-3 py-3 rounded-lg dark:text-white dark:border-darkborder peer-checked:border-primary500 peer-checked:shadow-lg dark:peer-checked:border-primary400">
                                  <div className="w-full text-center min-w-[80px]">
                                    <Image
                                      className={method.classes}
                                      src={method.logo}
                                      alt={method.label}
                                      width={93}
                                      height={93}
                                    />
                                    <span className="text-sm font-medium">
                                      {method.label}
                                    </span>
                                  </div>
                                </div>
                              </label>
                            ))}
                          </>
                        )}
                      />
                      {paymentMethods.formState.errors.paymentMethod && (
                        <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                          {
                            paymentMethods.formState.errors.paymentMethod
                              .message
                          }
                        </p>
                      )}
                    </div>

                    {/* Cardholder Name */}
                    <div>
                      <label className="block text-sm font-medium text-neutrals800 dark:text-gray-200 mb-1">
                        {t("checkout.cardholder_name")} <span className="text-sm text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        {...registerPayment("cardholderName", {
                          required: true,
                        })}
                        placeholder={t("checkout.cardholder_name_placeholder")}
                        className="w-full px-2 py-3 pe-9 rounded-lg text-sm placeholder:text-neutrals400 border border-neutrals100 bg-white text-neutrals800 leading-5 outline-none focus:border-primary500 dark:bg-card dark:focus:border-primary400 dark:border-darkborder dark:text-neutrals400"
                      />
                      {paymentMethods.formState.errors.cardholderName && (
                        <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                          {
                            paymentMethods.formState.errors.cardholderName
                              .message
                          }
                        </p>
                      )}
                    </div>

                    {/* Card Number */}
                    <div>
                      <label className="block text-sm font-medium text-neutrals800 dark:text-gray-200 mb-1">
                        {t("checkout.card_number")} <span className="text-sm text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        inputMode="numeric"
                        autoComplete="cc-number"
                        value={cardNumber}
                        {...registerPayment("cardNumber", {
                          required: true,
                        })}
                        onChange={handleChange}
                        placeholder={t("checkout.card_number_placeholder")}
                        className="w-full px-2 py-3 pe-9 rounded-lg text-sm placeholder:text-neutrals400 border border-neutrals100 bg-white text-neutrals800 leading-5 outline-none focus:border-primary500 dark:bg-card dark:focus:border-primary400 dark:border-darkborder dark:text-neutrals400"
                      />
                      {paymentMethods.formState.errors.cardNumber && (
                        <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                          {paymentMethods.formState.errors.cardNumber.message}
                        </p>
                      )}
                    </div>

                    {/* Expiration Date */}
                    <div>
                      <label className="block text-sm font-medium text-neutrals800 dark:text-gray-200 mb-1">
                        {t("checkout.expiration_date")} <span className="text-sm text-red-500">*</span>
                      </label>
                      <div className="grid grid-cols-2 gap-3">
                        {/* Expiry Month */}
                        <div>
                          <select
                            {...registerPayment("expiryMonth", { required: true })}
                            className="w-full px-2 py-3 pe-9 rounded-lg text-sm placeholder:text-neutrals400 border border-neutrals100 bg-white text-neutrals800 leading-5 outline-none focus:border-primary500 dark:bg-card dark:focus:border-primary400 dark:border-darkborder dark:text-neutrals400"
                            defaultValue=""
                          >
                            <option value="" disabled>
                              {t("checkout.month")}
                            </option>
                            <option value="01">{t("checkout.months.01")}</option>
                            <option value="02">{t("checkout.months.02")}</option>
                            <option value="03">{t("checkout.months.03")}</option>
                            <option value="04">{t("checkout.months.04")}</option>
                            <option value="05">{t("checkout.months.05")}</option>
                            <option value="06">{t("checkout.months.06")}</option>
                            <option value="07">{t("checkout.months.07")}</option>
                            <option value="08">{t("checkout.months.08")}</option>
                            <option value="09">{t("checkout.months.09")}</option>
                            <option value="10">{t("checkout.months.10")}</option>
                            <option value="11">{t("checkout.months.11")}</option>
                            <option value="12">{t("checkout.months.12")}</option>
                          </select>
                          {paymentErrors.expiryMonth && (
                            <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                              {paymentErrors.expiryMonth.message}
                            </p>
                          )}
                        </div>

                        {/* Expiry Year */}
                        <div>
                          <select
                            {...registerPayment("expiryYear", { required: true })}
                            className="w-full px-2 py-3 pe-9 rounded-lg text-sm placeholder:text-neutrals400 border border-neutrals100 bg-white text-neutrals800 leading-5 outline-none focus:border-primary500 dark:bg-card dark:focus:border-primary400 dark:border-darkborder dark:text-neutrals400"
                            defaultValue=""
                          >
                            <option value="" disabled>
                              {t("checkout.year")}
                            </option>
                            {getExpiryYears(10).map((year) => (
                              <option key={year} value={year}>
                                {year}
                              </option>
                            )
                            )}
                          </select>
                          {paymentErrors.expiryYear && (
                            <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                              {paymentErrors.expiryYear.message}
                            </p>
                          )}
                        </div>
                      </div>
                    </div>

                    {/* CVC */}
                    <div>
                      <label className="block text-sm font-medium text-neutrals800 dark:text-gray-200 mb-1">
                        {t("checkout.cvc")}  <span className="text-sm text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        inputMode="numeric"
                        autoComplete="cvc-number"
                        {...registerPayment("cvc", { required: true })}
                        value={cvcNumber}
                        onChange={handleChangeCVC}
                        placeholder={t("checkout.cvc_placeholder")}
                        className="w-full px-2 py-3 pe-9 rounded-lg text-sm placeholder:text-neutrals400 border border-neutrals100 bg-white text-neutrals800 leading-5 outline-none focus:border-primary500 dark:bg-card dark:focus:border-primary400 dark:border-darkborder dark:text-neutrals400"
                      />
                      {paymentMethods.formState.errors.cvc && (
                        <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                          {paymentMethods.formState.errors.cvc.message}
                        </p>
                      )}
                    </div>
                  </div>
                </form>
              </div>

              <div className="mt-6">
                <Button
                  type="button"
                  onClick={() => paymentSubmit()}
                  label={
                    isProcessing
                      ? t("checkout.processing")
                      : t("checkout.complete_payment")
                  }
                  disabled={isProcessing}
                  variant="secondary"
                  className="w-full justify-center"
                ></Button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
