import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { useRouter } from "next/router";
import AccountHeader from "@/components/shared/account-header";
import WishlistProductTable from "./product-listing/product-table";
import WishlistSkeleton from "./WishlistSkeleton";
import { useTranslation } from "react-i18next";
import { useWishlist } from "@/context/helpers/wishlist/WishlistContext";
import { useCart } from "@/context/helpers/cart/CartContext";
import { toast } from "react-toastify";
import Link from "next/link";
import { LOGIN_ROUTE } from "@/lib/constants";

export default function Wishlist() {
  const router = useRouter();
  const { t } = useTranslation("wishlist");
  const { wishlistItems, removeFromWish, isLoading, getWishlistItems } =
    useWishlist();
  const { addToCart } = useCart();
  const [isAddingToCart, setIsAddingToCart] = useState({});

  // Fetch wishlist items when page loads if we don't have any
  useEffect(() => {
    // Always fetch when page loads to ensure we have the latest data
    // This handles the case where we navigate from homepage to wishlist page
    getWishlistItems(LOGIN_ROUTE, true, true).catch((err) => {
      console.error("Failed to fetch wishlist items on page load:", err);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function handleRemove(productId) {
    // Find the item in the wishlist (use current items, not optimistic)
    // We need to find it before the optimistic update removes it
    const item = wishlistItems.find((item) => item.productId === productId);
    if (item) {
      removeFromWish(item, LOGIN_ROUTE);
      // Don't show success toast here - let the context handle it
      // The optimistic update will handle the UI update
    } else {
      // Item not found - might have been removed already, refresh the list
      toast.error(
        t("wishlist:messages.itemNotFound", "Item not found in wishlist")
      );
      getWishlistItems(LOGIN_ROUTE, false, false).catch((err) => {
        console.error("Failed to refresh wishlist:", err);
      });
    }
  }

  const handleAddToCart = async (item) => {
    const productId = item.productId;
    if (item.typeId === "configurable") {
      router.push(`/product/${productId}`);
      return;
    }

    setIsAddingToCart((prev) => ({ ...prev, [productId]: true }));
    try {
      await addToCart(
        {
          entityId: productId,
          variationId: item.variationId || 0,
        },
        1
      );
    } finally {
      setIsAddingToCart((prev) => ({ ...prev, [productId]: false }));
    }
  };

  // Show loading state with skeleton
  if (isLoading) {
    return <WishlistSkeleton />;
  }

  // Show empty state
  if (!wishlistItems || wishlistItems.length === 0) {
    return (
      <>
        <header>
          <AccountHeader title={t("wishlist:header.title")} />
        </header>
        <main className="container max-w-screen-xl px-5 py-16 mx-auto text-center xl:px-0">
          <h1 className="mb-4 text-3xl font-bold">
            {t("wishlist:empty.title")}
          </h1>
          <p className="mb-8 text-gray-600">{t("wishlist:empty.subtitle")}</p>
          <Button size="lg" className="bg-mainColor" asChild>
            <Link href="/">{t("wishlist:empty.cta")}</Link>
          </Button>
        </main>
      </>
    );
  }

  return (
    <>
      <header>
        <AccountHeader
          title={t("wishlist:header.title")}
          label1={t("wishlist:breadcrumb.home")}
          label2={t("wishlist:breadcrumb.wishlist")}
        />
      </header>

      <main className="container max-w-screen-xl px-5 py-8 mx-auto xl:px-0">
        <section className="w-full">
          <WishlistProductTable
            cartItems={wishlistItems}
            onRemove={handleRemove}
            stockStats={t("wishlist:table.stock.active")}
            onView={(productId) => router.push(`/product/${productId}`)}
            onAddToCart={handleAddToCart}
            isAddingToCart={isAddingToCart}
          />
        </section>
      </main>
    </>
  );
}
