"use client";
import ProductinBag from "@/app/components/user-dashboard/bag-item";
import CartSummary from "@/app/components/user-dashboard/cart-summary";
import { useCallback, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { toast } from "react-toastify";
import { setCartItemCount } from "../redux/cartSlice";
import { getCartList, removeFromCart, updateCartQuantity } from "../actions/cart";

interface Product {
  id: string;
  slug: string;
  cart_id: string;
  product_id: number;
  cart_type: string;
  main_item_image: {
    image_url: string;
  };
  design_house: {
    name: string;
  };
  product_name: string;
  product_image: string;
  price: number;
  quantity: number;
  size?: string;
  total_price?: string;
  external_id?: string;
  order_summary?: any;
}

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

  const getProductList = useCallback(async () => {
    try {
      // Use server action
      const data = await getCartList();
      
      if (!data.success) {
        throw new Error(data.message || 'Failed to fetch cart');
      }
     
      const cartItems = data.data || [];
      console.log("Cart items loaded:", cartItems);
      
      setProducts(cartItems);
      setTotalItem(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);
      
      dispatch(setCartItemCount({ totalCount: cartItems.length }));

      return data;
    } catch (error: any) {
      console.error("Error fetching cart:", error);
      toast.error(error.message || "Failed to load cart");
    }
  }, [dispatch]);

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

  // Called when child clicks "Remove"
  const handleRemove = async (cartId: string) => {
    try {
      // Use server action
      const result = await removeFromCart(cartId);

      if (!result.success) {
        console.error("Remove failed", result.message || "Unknown error");
        toast.error(result.message || "Failed to remove item");
        return;
      }

      toast.info("Item removed from the bag!", {
        toastId: "remove_item_from_bag",
      });

      // Re-fetch fresh list
      await getProductList();
    } catch (error: any) {
      console.error("Remove error:", error);
      toast.error(error.message || "Failed to remove item");
    }
  };

  // Called when a child reports a quantity change
  const handleQuantityChange = async (cartId: string, newQty: number) => {
    console.log("handleQuantityChange called with:", { cartId, newQty });
    
    if (!cartId) {
      console.error("Cart ID is missing!");
      toast.error("Unable to update quantity - cart ID missing");
      return;
    }

    try {
      // Use server action
      const result = await updateCartQuantity(cartId, newQty);
      
      console.log("Update cart result:", result);
      
      if (!result.success) {
        throw new Error(result.message || "Failed to update quantity");
      }

      // Re-fetch fresh cart
      await getProductList();
    } catch (error: any) {
      console.error("Failed to update quantity:", error);
      toast.error(error.message || "Failed to update quantity");
    }
  };

  return (
    <div className="py-14">
      <div className="wrapper">
        <div className="flex w-full flex-1 flex-col gap-4">
          <div className="flex w-full flex-col">
            <div className="flex flex-col">
              <h1 className="med">My bag</h1>
              <p>{totalItem} items{totalItem > 0 && ` - $${totalPrice}`}</p>
            </div>
            <div className="mt-2 flex w-full flex-col justify-between gap-5 align-top lg:flex-row">
              <div className="flex w-full flex-col gap-2 lg:w-[60%]">
                {products &&
                  products.map((product: any, index) => (
                    <ProductinBag 
                      key={`${product}_${index}`} 
                      bagItem={product} 
                      onQuantityChange={(newQty) =>
                        handleQuantityChange(product.cart_id, newQty)
                      }
                      onRemove={() => handleRemove(product.cart_id)}
                    />
                  ))}
              </div>
              <div className="flex-inline w-full lg:w-[50%] lg:max-w-[500px]">
                <CartSummary
                  totalItems={totalItem}
                  totalPrice={totalPrice}
                  itemTotal={totalPrice}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
