"use client";
import { useState, useEffect } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useDispatch } from "react-redux";
import Cookies from "js-cookie";
import { toast } from "react-toastify";
import { setCartItemCount } from "@/app/redux/cartSlice";
import { FormButton } from "@/app/components/form/forms";
import ProductSize from "@/app/components/product/product-size";
import { AWS_CDN_URL } from "@/utils/staticValues";
import { addToCart } from "@/app/actions/cart";
import { getCoCreationSession } from "@/app/actions/coCreation";

interface ProductActionsProps {
  product: any;
  variations: any[];
  sizes: any[];
  primaryImg: string;
  initialPrice: number;
  initialGalleryImages: any[];
}

export default function ProductActions({
  product,
  variations,
  sizes,
  primaryImg,
  initialPrice,
  initialGalleryImages,
}: ProductActionsProps) {
  const dispatch = useDispatch();
  const router = useRouter();

  const [productPrice, setProductPrice] = useState(initialPrice);
  const [galleryImages, setGalleryImages] = useState(initialGalleryImages);
  const [selectedVariationId, setSelectedVariationId] = useState("SET");
  const [selectedSize, setSelectedSize] = useState<string | null>(null);
  const [showSizeError, setShowSizeError] = useState(false);
  const [isAddingToBag, setIsAddingToBag] = useState(false);
  const [isAdded, setIsAdded] = useState(false);

  function variationPriceChanges(v: any) {
    setProductPrice(v.variation_price);
    setSelectedSize(null);
    setShowSizeError(false);
    window.dispatchEvent(new CustomEvent("variationPriceChanged", { detail: { price: v.variation_price } }));

    setGalleryImages([
      {
        id: v.id,
        image_url: v.variations_image === "null" ? null : v.variations_image,
        alt_text: v.variation_name,
      },
    ]);
  }

  useEffect(() => {
  const handleCartUpdate = (event: any) => {
    const removedProductId = event.detail?.productId;

    // ✅ only update if same product
    if (removedProductId === product?.id) {
      setIsAdded(false);
    }
  };

  window.addEventListener("cartUpdated", handleCartUpdate);

  return () => {
    window.removeEventListener("cartUpdated", handleCartUpdate);
  };
}, [product?.id]);

  function variationSetClick() {
    setGalleryImages(initialGalleryImages);
    setProductPrice(initialPrice);
    setSelectedSize(null);
    setShowSizeError(false);
    window.dispatchEvent(new CustomEvent("variationPriceChanged", { detail: { price: initialPrice } }));
  }

  const handleAddToBag = async () => {
    if (!selectedSize) {
      setShowSizeError(true);
      toast.error("Please select a size before adding to bag");
      return;
    }

    setIsAddingToBag(true);

    try {
      // Use server action
      const result = await addToCart(
        product?.id,
        selectedSize,
        selectedVariationId === "SET" ? "SET" : selectedVariationId,
        productPrice,
      );

      if (!result.success) {
        // Show the error message from server action
        toast.error(result.message || "Failed to add to bag");
        return;
      }

      // ✅ store time
      const key = `cart_added_${product?.id}`;
      localStorage.setItem(key, JSON.stringify({ time: Date.now() }));
      setIsAdded(true);

      const totalCount = result.data?.total_bag_item_count;
      if (totalCount !== undefined) {
        dispatch(setCartItemCount({ totalCount }));
      }
      toast.success("Added to bag successfully!");
    } catch (err) {
      console.log("Add to bag failed:", err);
      toast.error("Failed to add to bag. Please try again.");
    } finally {
      setIsAddingToBag(false);
    }
  };

  const handleCustomizeClick = async () => {
    try {
      // Call server action to get co-creation session
      // No need to pass userId - it will be extracted server-side from cookies
      const result = await getCoCreationSession(product?.id);

      if (!result.success) {
        // If login is required, redirect to login page
        if (result.requiresLogin) {
          // Store the backend URL for post-login redirect
          if (result.url && typeof window !== "undefined") {
            sessionStorage.setItem("post_login_redirect_url", result.url);

            // Redirect to login page with the backend URL as redirect parameter
            router.push(
              `/auth/login?redirect=${encodeURIComponent(result.url)}`,
            );
          } else {
            // Fallback if backend didn't return URL
            const fallbackUrl = `/product/${product?.id}?customize=true`;
            sessionStorage.setItem("post_login_redirect_url", fallbackUrl);
            router.push(
              `/auth/login?redirect=${encodeURIComponent(fallbackUrl)}`,
            );
          }
        } else {
          toast.error(
            result.message ||
              "Failed to start customization. Please try again.",
          );
        }
        return;
      }

      // User is logged in - store session_id and redirect directly
      if (result.session_id) {
        sessionStorage.setItem("session_id", result.session_id);
      }

      // Open the co-creation URL
      if (result.url && typeof window !== "undefined") {
        window.location.href = result.url;
      }
    } catch (error) {
      console.error("Error starting customization:", error);
      toast.error("Failed to start customization. Please try again.");
    }
  };

  const handleSizeChange = (size: string | null) => {
    setSelectedSize(size);
    if (size && showSizeError) {
      setShowSizeError(false);
    }
  };

  return (
    <>
      {variations && variations.length > 0 && (
        <div className="flex w-full flex-col gap-2 py-2">
          <div className="text-xs">{variations?.length} items in combo set</div>
          <div className="flex w-full flex-row gap-2 md:gap-4">
            {/* Static element */}
            <div className="flex max-w-18 flex-col gap-1">
              <div
                className={`cursor-pointer p-1 ${selectedVariationId === "SET" ? "border-2" : "border-1 border-dashed hover:border-solid"}`}
                onClick={() => {
                  variationSetClick();
                  setSelectedVariationId("SET");
                }}
              >
                <Image
                  src={`${AWS_CDN_URL}/${primaryImg}`}
                  alt="set"
                  width="48"
                  height="80"
                  className="img-responsive"
                />
              </div>
              <p className="text-xs">SET</p>
            </div>

            {/* Dynamic elements */}
            {variations.map((v) => (
              <div className="flex max-w-18 flex-col gap-1" key={v.id}>
                <div
                  className={`cursor-pointer p-1 ${selectedVariationId === v.id ? "border-2" : "border-1 border-dashed hover:border-solid"}`}
                  onClick={() => {
                    variationPriceChanges(v);
                    setSelectedVariationId(v.id);
                  }}
                >
                  <Image
                    src={`${AWS_CDN_URL}/${v.variations_image}`}
                    alt={v.variation_name}
                    width="48"
                    height="80"
                    className="img-responsive"
                  />
                </div>
                <div className="text-xs">{v.variation_name}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      <ProductSize
        psize={sizes}
        onSizeChange={handleSizeChange}
        selectedSize={selectedSize}
      />

      <div className="mt-5 flex flex-col gap-2">
        <div className="border-1 border-dashed border-gray-950/25 p-1 text-xs/4">
          This piece will ship within{" "}
          <span className="font-medium">
            {product?.production_lead_time_days} days
          </span>{" "}
          after reception of your paid order.
        </div>
      </div>

      <div className="flex w-full flex-col">
        <FormButton
          id="btn_design_buy"
          label={
            isAdded
              ? "Added to Cart"
              : isAddingToBag
                ? "Adding to Bag..."
                : "Add to Bag"
          }
          type="button"
          color="gray"
          hairline="amber"
          onClick={handleAddToBag}
          disabled={isAddingToBag || isAdded}
        />
      </div>

      <div className="flex w-full flex-col py-5">
        <button
          type="button"
          className="btn-outline w-full"
          onClick={handleCustomizeClick}
        >
          Customize
        </button>
      </div>

      {/* Price display - needs to be reactive */}
      <input type="hidden" data-price={productPrice} />
    </>
  );
}
