"use client";

import Link from "next/link";
import React, { useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import {
  getCartProducts,
  removeAllProductsFromCart,
  setCartOpen,
} from "@/store/slices/cart-slice";
import { useTranslations } from "next-intl";
import SectionTitle from "./section-title";
import CartProduct from "./cart-product";
import DeleteProductComponent from "./delete-product-component";

export default function QuickCart() {

  const t = useTranslations("cart");
  const dispatch = useDispatch();
  const { data, status } = useSelector((state: any) => state.cart);
  const { isAuthenticated } = useSelector((state: any) => state.auth);
  const hasFetchedRef = useRef(false);
  const prevAuthRef = useRef(isAuthenticated);

  const pathName = usePathname();
  const locale = pathName?.split("/")[1] || "ar";
  const cartItems = data?.data?.items ?? data?.items ?? [];

  useEffect(() => {
    if (
      !hasFetchedRef.current &&
      (data === null || (data?.data?.items == null && data?.items == null))
    ) {
      hasFetchedRef.current = true;
      dispatch(getCartProducts(locale) as any);
    }
  }, [dispatch, data, locale]);

  // On locale switch, refresh cartdetails so formatted totals match the new locale
  useEffect(() => {
    hasFetchedRef.current = false;
    dispatch(getCartProducts(locale) as any);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [locale]);

  // Refresh cart when order is successful (not cart operations)
  useEffect(() => {
    if (status === "success") {
      dispatch(getCartProducts(locale) as any);
    }
  }, [status, dispatch, locale]);

  // Reset fetch flag and fetch cart when user logs in or registers
  // This ensures we get the correct cart for the new user session
  useEffect(() => {
    // Check if authentication status changed from false to true (login/register)
    if (!prevAuthRef.current && isAuthenticated) {
      // Reset the fetch flag so cart can be fetched again
      hasFetchedRef.current = false;
      // Fetch the cart for the new user
      dispatch(getCartProducts(locale) as any);
    }
    // Update the previous auth state
    prevAuthRef.current = isAuthenticated;
  }, [isAuthenticated, dispatch, locale]);

  const [isOpen, setIsOpen] = useState(false);

  // if (isLoading) {
  //   return <Loading fullScreen={true} variant="spinner" size="xl" />;
  // }

  return (
    <div className="flex flex-col justify-between items-center gap-4 h-full min-h-0">
      <div className="flex flex-col flex-1 gap-4 w-full min-h-0">
        <SectionTitle
          title={t("quick-look")}
          titleStyle="text-center xl:text-2xl md:text-xl sm:text-lg text-base font-bold"
        />
        {cartItems.length > 0 ? (
          <p className="text-gray-500 text-xs md:text-sm text-center">
            {t("products-added-to-cart")}
          </p>
        ) : (
          <p className="w-full font-[600] text-red-color text-center">
            {t("no-products-yet")}
          </p>
        )}
        <div className="flex flex-col flex-1 items-end gap-3 w-full min-h-0 max-h-[60vh] overflow-y-auto cart-product">
          {cartItems.length > 0 &&
            cartItems.map((item: any) => (
              <CartProduct
                key={item?.product?.id || item?.id}
                product={item?.product}
                quantity={item?.quantity}
                deletedProductId={item?.id}
                cartItem={item}
              />
            ))}
        </div>
      </div>

      {/* Fixed bottom section for actions */}
      <div className="flex flex-col flex-shrink-0 gap-3 w-full">
        {cartItems.length > 0 && (
          <DeleteProductComponent
            setIsOpen={setIsOpen}
            isOpen={isOpen}
            action={() => dispatch(removeAllProductsFromCart() as any)}
            text={t("clear-all-products")}
            deleteMessage="delete-all-products"
          />
        )}
        {cartItems.length > 0 && (
          <div className="flex justify-center gap-2">
            <Link
              prefetch={true}
              href={`/${locale}/cart`}
              onClick={() => dispatch(setCartOpen(false))}
              className="w-full text-center md:text-sm text-xs bg-black text-white px-4 py-2 rounded-md hover:bg-black/80 border border-black hover:text-white transition-all duration-300"
            >
              {t("go-to-cart")}
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}
