"use client";
import ProductinBag from "@/app/components/user-dashboard/bag-item";
import CartSummary from "@/app/components/user-dashboard/cart-summary";

import Cookies from "js-cookie";
import { useEffect, useState } from "react";
interface Product {
  id: string;
  slug: string;
  main_item_image: {
    image_url: string;
  };
  design_house: {
    name: string;
  };
  product_name: string;
  price: number;
  quantity: number;
}
export default function UserBag() {
  const [products, setProducts] = useState<Product[]>([]);
  const [totalItem, setTotalItem] = useState(0);
  const [totalPrice, setTotalPrice] = useState(0);
  useEffect(() => {
    getProductList();
  }, []);

  async function getProductList() {
    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);
      
      // 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; // Return the data if needed
    } catch (error) {
      console.error("Failed to load cart data");
    }
  }
   // Update just one product’s quantity
   const handleQuantityChange222 = (index: number, newQty: number) => {
    setProducts((prev) =>
      prev.map((p, i) =>
        i === index
          ? {
              ...p,
              quantity: Math.max(1, Math.min(newQty, 99)), // clamp
            }
          : p
      )
    );
  };
 // Called when child clicks “Remove”
 const handleRemove = async (cartId: string) => {

  // 1) delete on server
  const res = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/cart/remove/${cartId}`, {
    method: "DELETE",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${Cookies.get("token")}`,
    },
    // body: JSON.stringify({ product_id: productId }),
  });
  if (!res.ok) {
    console.error("Remove request failed");
    return;
  }

  // 2) re-fetch fresh list
  await getProductList();
};

// Called when a child reports a quantity change
const handleQuantityChange = async (cartId: string, newQty: number) => {
  // 1) update on server
  const res = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/cart/update/${cartId}`, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${Cookies.get("token")}`,
    },
    body: JSON.stringify({ cart_id: cartId, quantity: newQty }),
  });
  if (!res.ok) {
    console.error("Quantity update request failed");
    return;
  }

  // 2) re-fetch fresh cart
  await getProductList();
};

  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 - $ {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-[50%]">
             
            {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}
              clientSecret={process.env.PAYMENT_SECRET!}
            />
            </div>
          </div>
        </div>
      </div>
    </div>
    </div>
  );
}
