"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 } from "react";
import { FaCheckCircle } from "react-icons/fa";
import { GoHome } from "react-icons/go";
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();

  useEffect(() => {
    async function confirm() {
      const payment_method = localStorage.getItem("payment_method");
      const response = await fetchData({
        endPoint: `/payment/success?paymentId=${invoiceId}&Id=${invoiceId}&payment_method=${payment_method}`,
        locale,
      });

      if (!response.error) {
        if (response?.status == "success") {
          await queryClient.refetchQueries({
            queryKey: ["/cart/items", locale],
          });
          localStorage.removeItem("payment_method");
          localStorage.removeItem("orderId");
          updateCart();
        }
      }
    }
    confirm();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return (
    <section>
      <div className="container  flex items-center justify-center  flex-col bg-[#FAFBFC] pb-10  h-[80vh] space-y-5 ">
        <FaCheckCircle
          size={50}
          className="text-green-500 text-2xl md:text-4xl"
        />
        <h1 className="font-bold text-2xl md:text-4xl">{t("success.title")}</h1>
        <Link href="/">
          <button className="btn btn-main-outline gap-x-2 flex items-center rounded-sm md:text-xl ">
            <GoHome className="font-bold" />
            {t(`success.button`)}
          </button>
        </Link>
      </div>
    </section>
  );
}
