"use client";
import fetchData from "@/api/fetch-data";
import { getQueryClient } from "@/app/get-query-client";
import useCart from "@/stores/cart";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { GoHome } from "react-icons/go";
import { IoCloseCircle } from "react-icons/io5";

export default function Page() {
  const queryClient = getQueryClient();
  const t = useTranslations("payment");
  const searchParams = useSearchParams();
  const invoiceId = searchParams.get("invoice_id");
  const locale = useLocale();
  const { updateCart } = useCart();
  const [referenceNumber, setReferenceNumber] = useState(null);

  useEffect(() => {
    async function confirm() {
      const response = await fetchData({
        endPoint: `/payment/pending?invoice_id=${invoiceId}`,
        locale,
      });

      if (!response.error) {
        if (response?.status == "success") {
          await queryClient.refetchQueries({
            queryKey: ["/cart/items", locale],
          });
          setReferenceNumber(response?.data?.reference_id);
          localStorage.removeItem("payment_method");
          localStorage.removeItem("orderId");
          updateCart();
        }
      }
    }
    confirm();
  }, []);

  return (
    <section>
      <div className="container  flex items-center justify-center  flex-col bg-[#FAFBFC] pb-10  h-[80vh] space-y-5 ">
        <IoCloseCircle
          size={50}
          className="text-yellow-500 text-2xl md:text-4xl"
        />
        <h1 className="font-bold text-2xl md:text-4xl">{t("pending.title")}</h1>

        {referenceNumber && (
          <>
            <p className="text-center font-bold text-xl">
              {t("pending.onlinePayment")}
            </p>
            <p className="text-center font-bold text-xl mx-2">
              {t("pending.referenceNumber")} :
              <span className="text-main">{referenceNumber}</span>
            </p>
          </>
        )}
        <Link href="/">
          <button className="btn btn-main-outline gap-x-2 flex items-center rounded-sm md:text-xl ">
            <GoHome />
            {t("pending.button")}
          </button>
        </Link>
      </div>
    </section>
  );
}
