"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="min-h-screen bg-gray-50">
    <div className="max-w-7xl mx-auto px-4 md:px-6 py-8">

      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center justify-between bg-gradient-to-r from-pink-50 via-rose-50 to-red-50 border border-rose-100 rounded-3xl p-6 shadow-sm">
          <div className="flex items-center gap-4">
            <div className="bg-white p-4 rounded-2xl shadow-sm">
              <Heart className="w-7 h-7 text-rose-600 fill-rose-600" />
            </div>

            <div>
              <h1 className="text-3xl font-bold text-gray-900">
                My Wishlist
              </h1>

              <p className="text-gray-500 mt-1">
                Save your favourite products and shop later
              </p>
            </div>
          </div>

          <div className="bg-white px-5 py-3 rounded-2xl shadow-sm border">
            <p className="text-xs uppercase tracking-wider text-gray-500">
              Items
            </p>

            <p className="text-3xl font-bold text-rose-600">
              {count}
            </p>
          </div>
        </div>
      </div>

      {/* Wishlist Content */}
      {items?.length === 0 ? (
        <div className="bg-white rounded-3xl border shadow-sm p-12 text-center">
          <div className="w-24 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-2xl font-semibold text-gray-900">
            Your wishlist is empty
          </h2>

          <p className="text-gray-500 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-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
            {items.map((item: any) => (
              <WishlistCard
                key={item._id}
                item={item}
                onRemove={() =>
                  removeFromWishlist({
                    product_id: item?.product_id?._id,
                  })
                }
              />
            ))}
          </div>
        </>
      )}
    </div>
  </div>
);
}