"use client";
import { useRouter } from "next/navigation";
import { useEffect, useState, useCallback } from "react";
import Cookies from "js-cookie";
import { useDispatch, useSelector } from "react-redux";
import { setCartItemCount } from "@/app/redux/cartSlice";
import { LinkButton } from "@/app/components/form/forms";

interface Product {
  id: string;
  slug: string;
  main_item_image: {
    image_url: string;
  };
  design_house: {
    name: string;
  };
  product_name: string;
  price: number;
  cart_id: string;
  quantity: number;
}

export default function MiniCart() {
  const [products, setProducts] = useState<Product[]>([]);
  const [totalItem, setTotalItem] = useState(0);
  const [totalPrice, setTotalPrice] = useState(0);
  const dispatch = useDispatch();
  const router = useRouter();

  const getCartItemList = useCallback(async () => {
    try {
      const response = await fetch(`/api/cart/list`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include", // Include cookies for authentication
      });

      if (!response.ok) {
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      }

      const data = await response.json();
      const cartItems = data.data || [];
      setProducts(cartItems);
      setTotalItem(cartItems.length);
      dispatch(setCartItemCount({ totalCount: cartItems.length }));

      // Calculate total price from cart items (price * quantity)
      const calculatedTotal = cartItems.reduce((sum: number, item: Product) => {
        const itemPrice = Number(item.price) || 0;
        const itemQuantity = Number(item.quantity) || 1;
        return sum + itemPrice * itemQuantity;
      }, 0);
      setTotalPrice(calculatedTotal);

      return data;
    } catch (error) {
      console.error("Error fetching cart items:", error);
    }
  }, [dispatch]);

  useEffect(() => {
    getCartItemList();
  }, [getCartItemList]);

  const handleContinueShopping = () => {
    router.push("/category");
  };

  const handleRemoveItem = async (cart_id: string, product_id: string) => {
    const confirmed = window.confirm(
      "Are you sure you want to remove this item?",
    );
    if (!confirmed) return;
    try {
      const response = await fetch(`/api/cart/remove/${cart_id}`, {
        method: "DELETE",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include", // Include cookies for authentication
      });
      if (!response.ok) throw new Error(`Delete failed: ${response.status}`);
      // ✅ REMOVE localStorage key
      const key = `cart_added_${product_id}`;
      localStorage.removeItem(key);
      // ✅ OPTIONAL: trigger UI sync across tabs/components
      // ✅ 🔥 notify whole app
      window.dispatchEvent(
        new CustomEvent("cartUpdated", {
          detail: { productId: product_id },
        }),
      );
      getCartItemList();
    } catch (error) {
      console.error("Error removing item:", error);
    }
  };

  return (
    <div className="pb-10">
      <div>
        <p className="font-bogart text-base tracking-wide">Your bag</p>
        <div className="flex flex-row items-center justify-between align-middle font-medium">
          <p className="text-sm">
            {totalItem} {totalItem <= 1 ? "product" : "products"}
          </p>
          <p>{totalItem > 0 && `$${totalPrice}`}</p>
        </div>
      </div>
      <div className="flex max-h-[280px] w-full overflow-y-auto py-5">
        <div className="flex w-full flex-col">
          <ul className="flex w-full flex-col gap-0.5 bg-gray-200 text-sm">
            {products.map((product, index) => (
              <li
                key={`${product.id}_${index}`}
                className="flex flex-row items-center justify-between gap-4 bg-white py-4"
              >
                <div className="inline-flex w-[60%] flex-col">
                  <p>{product.product_name}</p>
                  <p className="text-xs uppercase">QTY:{product.quantity}</p>
                </div>
                <div className="inline-flex w-[25%] justify-end">
                  $ {product.price}
                </div>
                <div className="inline-flex w-[10%] justify-end">
                  <button
                    onClick={() =>
                      handleRemoveItem(product.cart_id, product.id)
                    }
                    className="p-2"
                  >
                    <i className="icon-[iconamoon--close-duotone]" />
                  </button>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
      <div className="py-2 pt-4">
        <div className="btn-wrap">
          {totalItem > 0 ? (
            <>
              <LinkButton
                id="link_mini_cart_checkout"
                label="Proceed to checkout"
                href="/bag"
                color="gray"
                hairline="amber"
              />
              <div className="mt-6 flex flex-col items-center justify-center">
                <button className="btn-link" onClick={handleContinueShopping}>
                  Continue Shopping
                </button>
              </div>
            </>
          ) : (
            <button className="btn-hero" onClick={handleContinueShopping}>
              Continue Shopping
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
