"use client";

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

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

  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 ${clienttoken}`
          }
        });
        if(res?.data?.success){
          setItems(res.data?.data)
          setCount(res.data?.count)
        }
      } catch (error) {
        console.error("Error fetching wishlist", error);
      }
    };    
    useEffect(() => {
      console.log('Items ^^^', items)
    }, [items])
  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,
        });

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

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

  return (
    <div className="p-0">
      {/* Header */}
      <div className="mb-4 md:mb-6">
        <div className="flex items-center justify-between bg-[var(--theme-white)] border border-[rgba(var(--primary),0.20)] rounded-3xl p-4 md:p-6">
          <div className="flex items-center gap-4">
            <div className="p-3 md:p-4 rounded-lg md:rounded-2xl bg-[var(--theme-white)] border border-[rgba(var(--primary),0.20)]">
              <Heart className="w-4 h-4 md:w-7 md:h-7 text-rose-600 fill-rose-600" />
            </div>

            <div>
              <h2 className="text-lg md:text-xl lg:text-2xl text-3xl font-bold text-[rgba(var(--secondary),1)]">
                My Wishlist
              </h2>

              <p className="text-xs md:text-sm lg:text-sm text-base text-gray-500 mt-1">
                Save your favourite products and shop later
              </p>
            </div>
          </div>

          <div className="px-2 py-2 md:px-5 md:py-3 rounded-2xl text-center bg-[var(--theme-white)] border border-[rgba(var(--primary),0.20)]">
            <p className="text-xs uppercase tracking-wider text-gray-500">
              Items
            </p>
            <p className="text-xl md:text-3xl font-bold text-rose-600">
              {count}
            </p>
          </div>
        </div>
      </div>
      {/* Wishlist Content */}
      {items?.length === 0 ? (
        <div className="rounded-xl md:rounded-3xl bg-[var(--theme-white)] border border-[rgba(var(--primary),0.20)] p-6 md:p-12 text-center">
          <div className="w-18 h-18 md:w-24 md:h-24 bg-rose-50 rounded-full flex items-center justify-center mx-auto mb-6">
            <Heart
              size={42}
              className="text-rose-500"
            />
          </div>

          <h2 className="text-xl md:text-2xl font-semibold text-gray-900">
            Your wishlist is empty
          </h2>

          <p className="text-gray-500 text-xs md:text-base mt-2">
            Browse products and save your favourites here.
          </p>
        </div>
      ) : (
        <>
          {/* Section Header */}
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-lg font-semibold text-gray-900">
              Saved Products
            </h2>

            <span className="text-sm text-gray-500">
              {count} item{count !== 1 ? "s" : ""}
            </span>
          </div>

          {/* Products Grid */}
          <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-2 md:gap-4">
            {items.map((item: any) => (
              <WishlistCard
                key={item._id}
                item={item}
                onRemove={() =>
                  removeFromWishlist({
                    product_id: item?.product_id?._id,
                  })
                }
              />
            ))}
          </div>
        </>
      )}
    </div>
  );
}