"use client";
import postData from "@/api/post-data";
import { toastError, toastSuccess } from "@/services/custom-toast";
import useShippingPrice from "@/stores/shipping-price";
import { useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
import { CiDeliveryTruck } from "react-icons/ci";
import { FaSpinner } from "react-icons/fa";

export default function ShippingMethod({ shippingData, paymentId }) {
  const t = useTranslations("checkout-info");
  const [options, setOptions] = useState([]);
  const [selectedCompany, setSelectedCompany] = useState(null); // Initialize state for the selected company
  const [orderId, setOrderId] = useState(null); // Initialize state for the selected company
  const [isComplete, startComplete] = useTransition();
  const [isPending, startTransition] = useTransition();
  const router = useRouter();
  const queryClient = useQueryClient();
  const { setPrice } = useShippingPrice();

  // get shipping options
  useEffect(() => {
    async function getShippingMethods() {
      const formData = new FormData();
      formData.append("country_id", shippingData.country);
      formData.append("city_id", shippingData.city);

      const { error, data } = await postData({
        endPoint: "/cart/available_shipping_methods",
        body: formData,
      });

      if (!error) {
        const shippingMethods = Object.values(data ?? []);
        setOptions(shippingMethods);
      }
    }
    getShippingMethods();
  }, [shippingData.city, shippingData.country]);

  // handle selection
  const handleSelection = (optionId) => {
    setSelectedCompany(optionId); // Update state when a radio button is selected
  };

  // complete order
  async function completeOrder() {
    if (selectedCompany) {
      const values = {
        ...shippingData,
        shipping_option: selectedCompany,
        shipping_required: 1,
        buttonType: "no",
      };
      const formData = new FormData();
      Object.entries(values).forEach(([key, value]) => {
        formData.append(key, value);
      });

      const { code, message, data } = await postData({
        endPoint: "/cart/completing_order",
        body: formData,
      });
      if (code != 200) {
        return toastError(message);
      }
      toastSuccess(message);
      setOrderId(data?.order_id);
      setSelectedCompany(null);
      if (shippingData?.payment_method == 16) {
        setPrice(0);
        router.replace("/");
        setTimeout(() => updateCart(), 2500);
        return;
      }
    }
  }

  // do pay functions
  async function doPay() {
    if (orderId) {
      localStorage.setItem("orderId", orderId);
      const formData = new FormData();
      formData.append("payment_method", shippingData?.payment_method);
      formData.append("order_id", orderId);
      const response = await postData({
        endPoint: "/payment/redirect",
        body: formData,
      });
      if (!response.error) {
        if (response?.message == "success") {
          setPrice(0);
          queryClient.invalidateQueries({ queryKey: ["/cart/items"] });
          // window.location.href = response?.data?.data?.url;

          router.replace(response?.data?.url);
        }
      } else {
        toastError(response.message);
      }
    }
  }

  return (
    <section className="space-y-4">
      <h1 className="text-xl  font-bold">{t("shipping-method")}</h1>
      <div className="space-y-4">
        {options.map((option) => (
          <label
            key={option.company_id}
            className={`p-2 md:p-4 flex justify-between border-2 items-center rounded cursor-pointer ${
              selectedCompany === option.option_id ? "border-black" : ""
            }`} // Add border color if selected
          >
            <input
              type="radio"
              name="company"
              value={option.option_id}
              className="hidden"
              onChange={() => handleSelection(option.option_id)}
            />
            <div className="flex gap-4 items-center">
              <CiDeliveryTruck className="size-6" />
              <div>
                <h2 className="text-lg font-semibold">
                  {option.company_title}
                </h2>
                <p className="text-xs text-gray-500">{option.company_delay}</p>
              </div>
            </div>
            <p className="text-gray-500 font-medium text-sm">
              {option.company_cost_text}
            </p>
          </label>
        ))}
      </div>
      {selectedCompany && (
        <button
          type="submit"
          className="btn btn-btnColor-default w-full flex items-center justify-center"
          onClick={() => startTransition(completeOrder)}
        >
          {isPending ? (
            <>
              <FaSpinner size={20} className="text-white animate-spin" />
              &nbsp;{t("confirmingOrder")}
            </>
          ) : (
            <>{t("confirmOrder")}</>
          )}
        </button>
      )}

      {orderId && paymentId != 16 && (
        <button
          type="submit"
          className="btn btn-btnColor-default w-full flex items-center justify-center"
          onClick={() => startComplete(doPay)}
        >
          {isComplete ? (
            <>
              <FaSpinner size={20} className="text-white animate-spin" />
              &nbsp;{t("completingPayment")}
            </>
          ) : (
            <>{t("completePayment")}</>
          )}
        </button>
      )}
    </section>
  );
}
