"use client";
import React, { useState, useEffect } from "react";
import Cookies from "js-cookie";
import { useRouter, usePathname } from "next/navigation";
import { toast } from "react-toastify";
import { useSelector, useDispatch } from "react-redux";
import { addToWishlist, removeFromWishlist } from "@/app/redux/wishlistSlice";

interface RootState {
  wishlist: {
    items: any[];
    productIds: string[];
    isLoaded: boolean;
  };
}

export default function LikeBtn({ productId, wishType = 'PRODUCT' }: { productId: string | number, wishType: string }) {
  const dispatch = useDispatch();
  const router = useRouter();
  const pathname = usePathname();
  
  // Get wishlist state from Redux
  const wishlistProductIds = useSelector((state: RootState) => state.wishlist.productIds);
  const isWishlistLoaded = useSelector((state: RootState) => state.wishlist.isLoaded);
  const fullWishlistState = useSelector((state: RootState) => state.wishlist);
  
  //console.log("Redux wishlist state:", fullWishlistState);
  
  // Check if product is in wishlist
  const [isLiked, setIsLiked] = useState(false);

  useEffect(() => {
    // Update isLiked state based on wishlist data
    const productIdStr = String(productId);
    const isInWishlist = wishlistProductIds.includes(productIdStr);
    // console.log("LikeBtn check:", {
    //   productId: productIdStr,
    //   wishlistProductIds,
    //   isInWishlist
    // });
    setIsLiked(isInWishlist);
  }, [wishlistProductIds, productId]);

  const handleLike = async (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();

    // Check if user is logged in (use token_client as token is httpOnly)
    const token = Cookies.get("token_client");
    
    if (!token) {
      toast.error("Please login in order to add to wishlist", {
        toastId: "wishlist_login_required",
      });
      router.push(`/auth/login?redirect=${encodeURIComponent(pathname)}`);
      return;
    }

    // Optimistically update UI
    const newLikedState = !isLiked;
    setIsLiked(newLikedState);

    try {
      // Use Next.js API route which handles authentication server-side
      const response = await fetch('/api/wishlist/add', {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ product_id: productId, product_type: wishType }),
      });
      
      const data = await response.json();
      
      if (response.ok) {
        // Update Redux state
        if (newLikedState) {
          dispatch(addToWishlist({ 
            productId: String(productId), 
            id: productId,
            wish_type: wishType 
          }));
          toast.success("Added to wishlist", { toastId: "wishlist_add_success" });
        } else {
          dispatch(removeFromWishlist(String(productId)));
          toast.success("Removed from wishlist", { toastId: "wishlist_remove_success" });
        }
      } else {
        // Revert on failure
        setIsLiked(!newLikedState);
        toast.error("Failed to update wishlist", { toastId: "wishlist_error" });
      }
    } catch (err) {
      console.error("Wishlist error:", err);
      // Revert on error
      setIsLiked(!newLikedState);
      toast.error("Something went wrong. Please try again.", { toastId: "wishlist_error" });
    }
  };

  const handleSubmit = async (e: any) => {
    e.preventDefault();

    try {
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/profile/onboarding/step3`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${Cookies.get("token")}`,
        },
        body: JSON.stringify({ proidct_id: productId }),
      });
      const data = await response.json();
    } catch (err) {
      console.log("Something went wrong. Please try again.");
    }
  };
  return (
    <button
      onClick={handleLike}
      name={`pid_${productId}`}
      id={`pid_${productId}`}
      aria-label={isLiked ? "Remove from wishlist" : "Add to wishlist"}
      className="flex h-12 w-12 flex-col items-center justify-center overflow-hidden rounded-full p-2 hover:bg-white/25"
    >
      <span
        className={`${isLiked ? "bg-gray-950" : "border-transparent"} flex h-full w-full items-center justify-center overflow-hidden rounded-full border-1 duration-300`}
      >
        <i
          className={`${isLiked ? "icon-[mingcute--heart-fill] bg-gray-100" : "icon-[mingcute--heart-line]"}`}
        ></i>
      </span>
    </button>
  );
}
