"use client";

import { apiCall } from "@/utils/callApi";
import { Heart } from "lucide-react";
import { useEffect, useState } from "react";
import WishlistCard from "./_components/WishlistCard";
import useAuth from "@/hooks/useAuth";

export default function WishlistPage() {
  const [items, setItems] = useState<any[]>([])
  const [count, setCount] = useState<number>(0)
  const { clienttotken } = useAuth()

  const fetchWishList = async () => {
      try {
        const customerRaw = localStorage.getItem("customer");
        const guestId = localStorage.getItem("guestId");

        const customer = customerRaw ? JSON.parse(customerRaw) : null;

        const userId = customer?.id;

        let url = "/clientapi/wishlist?";

        if (userId) {
          url += `user_id=${userId}`;
        } else if (guestId) {
          url += `guest_id=${guestId}`;
        } else {
          console.log("No user or guest found");
          return;
        }

        // console.log("Wishlist URL:", url);

        const res = await apiCall<any>(url, {
          headers: {
            Authorization: `Bearer ${clienttotken}`
          }
        });
        if(res?.data?.success){
          setItems(res.data?.data)
          setCount(res.data?.count)
        }
      } catch (error) {
        console.error("Error fetching wishlist", error);
      }
    };    

  const removeFromWishlist = async ({
      product_id,
    }: {
      product_id: string;
    }) => {
      try {
        const customerRaw = localStorage.getItem("customer");
        const guestId = localStorage.getItem("guestId");

        const customer = customerRaw ? JSON.parse(customerRaw) : null;

        const payload: any = {
          product_id: product_id,
        };

        if (customer?.id) {
          payload.user_id = customer.id;
        } else if (guestId) {
          payload.guest_id = guestId;
        } else {
          console.log("No user or guest found");
        return;
      }
      // console.log('Payload ^^^^^', product_id)
        const res = await apiCall<any>("/clientapi/wishlist", {
          method: "DELETE",
          body: payload,
          headers: {
            Authorization: `Bearer ${clienttotken}`
          }
        });

        if(res?.data?.success){
          fetchWishList()
        }
      } catch (error) {
        console.error("Error removing wishlist item:", error);
        throw error;
      }
    };

  useEffect(() => {
    fetchWishList()
  }, [])

  return (
    <div>
      <h1 className="text-2xl font-semibold mb-4">My Wishlist {count ?? `(${count} Items)`}</h1>
      {items?.length === 0 ? <div className="bg-white rounded-xl shadow p-8 text-center">
        <Heart size={48} className="mx-auto text-gray-400 mb-4" />
        <p className="text-gray-500">Your wishlist is empty</p>
      </div>
      : items?.map((item: any) => 
        <WishlistCard 
          item={item}
          onRemove={() => removeFromWishlist({ product_id: item?.product_id?._id })}
        /> 
      )}
    </div>
  );
}