import { useEffect, useState, useRef } from "react";
import axios from "axios";
import { useRouter } from "next/router";
import Cookies from "js-cookie";
import { SyncOutlined } from "@ant-design/icons";
import { Spin } from "antd";
import toast from "react-hot-toast";
import ConfirmOrder from "./confirmOrder";
import { useSearchParams } from "next/navigation";

const antIcon = <SyncOutlined style={{ fontSize: 44, color: "#fff" }} spin />;

const SmartCashPaymentCallback = () => {
  const [paymentStatus, setPaymentStatus] = useState<string | null>(null);
  const router = useRouter();
  const { order_Id } = router.query;
  const [isOrderPlace, setOrderPlace] = useState<any>();
  const [loading, setLoading] = useState(true);
  const productId = useSearchParams().get("productId");
  const startTimeRef = useRef<number>(Date.now());
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  const authToken = Cookies.get("jazz_token");

  const axiosInstance = axios.create({
    baseURL: "https://api.jazzagain.com/public/index.php",
    headers: {
      authorization: `Bearer ${authToken}`,
    },
  });

  const handleTransactionTimeout = () => {
    setLoading(false);
    toast.error("Transaction timeout! Please try again.");
    router.push({
      pathname: `/payment-error`,
      query: {
        productId,
        reason: "timeout"
      },
    });
  };

  const clearAllTimers = () => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    if (intervalRef.current) {
      clearTimeout(intervalRef.current);
      intervalRef.current = null;
    }
  };

  useEffect(() => {
    if (order_Id) {
      // Set timeout for 1 minute (60000ms)
      timeoutRef.current = setTimeout(() => {
        handleTransactionTimeout();
      }, 60000);

      const verifyPayment = async () => {
        try {
          // Check if 1 minute has passed
          const elapsedTime = Date.now() - startTimeRef.current;
          if (elapsedTime >= 60000) {
            handleTransactionTimeout();
            return;
          }

          const response = await axiosInstance.get(
            `/api/user/orders/${order_Id}/edit`
          );

          const myPaymentStatus = response.data.order.paymentStatus;
          setPaymentStatus(myPaymentStatus);

          // If payment status is "Transaction Is In Progress", check again after a delay
          if (myPaymentStatus === "TIP" || myPaymentStatus === "Transaction Is In Progress") {
            setLoading(true);
            intervalRef.current = setTimeout(verifyPayment, 5000); // Retry after 5 seconds
          } else if (myPaymentStatus === "TS" || myPaymentStatus === "Success") {
            try {
              clearAllTimers(); // Clear timeout when payment succeeds
              const res = await axiosInstance.get(
                `/api/user/orders/${order_Id}/edit`
              );
              setOrderPlace(res.data.order);
              setLoading(false); // Stop loading when the payment is "Paid"
            } catch (error) {
              console.error("Error fetching or processing data:", error);
              clearAllTimers();
              return toast.error("Error fetching data !");
            }
          } else if (myPaymentStatus === "TF" || myPaymentStatus === "Failed") {
            try {
              clearAllTimers(); // Clear timeout when payment fails
              const res = await axiosInstance.get(
                `/api/user/orders/${order_Id}/edit`
              );
              setLoading(false);
              return router.push({
                pathname: `/payment-error`,
                query: {
                  productId,
                },
              });
            } catch (error) {
              console.error("Payment Error", error);
              clearAllTimers();
              return toast.error("Payment Error");
            }
          } else {
            console.error("Payment Error");
            clearAllTimers();
            return toast.error("Payment Error");
          }
        } catch (error) {
          console.error("Payment Error", error);
          clearAllTimers();
          return toast.error("Payment Error");
        }
      };
      verifyPayment();
    }

    // Cleanup function to clear timers when component unmounts
    return () => {
      clearAllTimers();
    };
  }, [order_Id]);

  return (
    <div>
      {loading ? (
        <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-70 z-50 ">
          <div className="text-white text-2xl text-center">
            <Spin indicator={antIcon} className="m-4" />
            <br />
            Your transaction is in process...
          </div>
        </div>
      ) : paymentStatus === "TS" || paymentStatus === "Success" ? (
        <ConfirmOrder details={isOrderPlace} />
      ) : null}
    </div>
  );
};

export default SmartCashPaymentCallback;