"use client";
import ProductThumb from "@/app/components/cards/product-thumb";
import { RadioChip } from "@/app/components/chips";
import { useEffect, useState, useCallback } from "react";
import { useDispatch } from "react-redux";
import { setCartItemCount } from "@/app/redux/cartSlice";
import { setWishlist } from "@/app/redux/wishlistSlice";
import { toast } from "react-toastify";

interface Product {
  id: string;
  slug: string;
  main_item_image: {
    image_url: string;
  };
  design_house: {
    name: string;
  };
  product_name: string;
  price: number;
  wish_type: string;
}

export default function Wislists() {
  const [products, setProducts] = useState<Product[]>([]);
  const [filteredProducts, setFilteredProducts] = useState<Product[]>([]);
  const [activeTab, setActiveTab] = useState("ALL");
  const [totalItem, setTotalItem] = useState(0);
  const [isAddingToBag, setIsAddingToBag] = useState(false);
  const [isRemoving, setIsRemoving] = useState<string | null>(null);
  const dispatch = useDispatch();

  const tabs = [
    { id: "ALL", label: "ALL" },
    { id: "PRODUCT", label: "PRODUCT" },
    { id: "FABRIC", label: "FABRIC" },
    { id: "SILHOUETTES", label: "SILHOUETTES" },
    { id: "TECHNIQUE", label: "TECHNIQUE" },
    { id: "ARTWORK", label: "ARTWORK" },
  ];

  const getProductList = useCallback(async () => {
    try {
      const response = await fetch("/api/wishlist/list", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });

      if (!response.ok) {
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      }

      const data = await response.json();

      console.log("Wishlist API response:", data);

      setProducts(data.data);
      setFilteredProducts(data.data);
      setTotalItem(data.data.length);

      // Update Redux wishlist state
      dispatch(setWishlist(data.data));

      return data;
    } catch (error) {
      console.error("Error fetching category list:", error);
    }
  }, [dispatch]);

  const filterProducts = useCallback(() => {
    if (activeTab === "ALL") {
      setFilteredProducts(products);
      setTotalItem(products.length);
    } else {
      const filtered = products.filter(
        (product) => product.wish_type === activeTab,
      );
      setFilteredProducts(filtered);
      setTotalItem(filtered.length);
    }
  }, [products, activeTab]);

  useEffect(() => {
    getProductList();
  }, [getProductList]);

  useEffect(() => {
    filterProducts();
  }, [filterProducts]);

  const handleTabChange = (tabId: string) => {
    setActiveTab(tabId);
  };

  const handleAddToBag = async (product_id: number, price: number) => {
    setIsAddingToBag(true);
    try {
      const p = { product_id, size: "S", price };
      const response = await fetch("/api/cart/add", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(p),
      });
      const data = await response.json();
      const totalCount = data?.data?.total_bag_item_count;
      dispatch(setCartItemCount({ totalCount }));
    } catch (err) {
      console.log("Add to bag failed:", err);
      toast.error("Login to add to Bag");
    } finally {
      setIsAddingToBag(false);
    }
  };

  const handleRemoveFromWishlist = async (wishListId: string) => {
    const confirmRemove = window.confirm(
      "Are you sure you want to remove this item from your wishlist?",
    );
    if (!confirmRemove) return;

    setIsRemoving(wishListId);
    try {
      const response = await fetch("/api/wishlist/remove", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ wish_list_id: wishListId }),
      });

      if (!response.ok) {
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      }

      await response.json();
      await getProductList();
      toast.success("Item removed from wishlist successfully!");
    } catch (error) {
      console.error("Error removing item from wishlist:", error);
      toast.error("Failed to remove item from wishlist");
    } finally {
      setIsRemoving(null);
    }
  };

  const handleCreation = async (co_creation_url: string) => {
    try {
      // Use the new generic co-creation API route
      const response = await fetch(`/api/co-creation/start`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ co_creation_url }),
      });

      if (!response.ok) {
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      }

      const r = await response.json();

      if (r.data?.session_id) {
        sessionStorage.setItem("session_id", r.data.session_id);
      }

      if (r.data?.url) {
        window.location.href = r.data.url;
      }
    } catch (error) {
      console.error("Error starting co-creation:", error);
      toast.error("Failed to start co-creation");
    }
  };

  return (
    <div className="flex w-full flex-1 flex-col gap-4">
      <div className="flex flex-col">
        <h1 className="med">Wishlist</h1>
        <p>{totalItem} items</p>
      </div>

      {/* Tabs */}
      <div className="flex flex-wrap gap-2 border-b border-gray-200 pb-4">
        {tabs.map((tab) => (
          <RadioChip
            key={tab.id}
            id={tab.id}
            label={tab.label}
            name="wishlist-tabs"
            checked={activeTab === tab.id}
            onChange={() => handleTabChange(tab.id)}
          />
        ))}
      </div>

      <div className="grid w-full grid-cols-1 gap-8 sm:grid-cols-2 lg:grid-cols-3 xl:gap-10">
        {filteredProducts.map((product: any, index) => (
          <div key={`${product.id}_${index}`} className="flex w-full flex-col">
            <ProductThumb
              key={product.id}
              image={product?.image}
              hoverImg={product?.image}
              title={product?.name}
              price={product?.price}
              url={`/product/${product?.slug}`}
              designHouse={product?.design_house?.name || ""}
              pid={product?.id}
              showLikeBtn={false}
              wishType={product?.wish_type}
            />
            <div className="flex w-full justify-between align-middle">
              {product?.wish_type === "PRODUCT" ? (
                <button
                  className="btn-outline"
                  onClick={() =>
                    handleAddToBag(product.master_id, product.price)
                  }
                  disabled={isAddingToBag}
                >
                  {isAddingToBag ? "Adding..." : "Add to Bag"}
                </button>
              ) : (
                <button
                  className="btn-outline"
                  onClick={() => handleCreation(product.co_creation_url)}
                  disabled={isAddingToBag}
                >
                  Start Co-Creation
                </button>
              )}
              <button
                className="btn-link"
                onClick={() => handleRemoveFromWishlist(product.wish_list_id)}
                disabled={isRemoving === product.id}
              >
                Remove
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
