import { useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { toast } from 'sonner';
import { useCartStore } from '@/lib/cart/store';

/**
 * Hook to handle add-to-cart from URL parameters
 * Supports both simple and variable products
 * 
 * URL formats:
 * - Simple product: ?add-to-cart=123
 * - Variable product: ?add-to-cart=123&variation_id=456
 * - With quantity: ?add-to-cart=123&quantity=2
 * - Direct to checkout: ?add-to-cart=123&redirect=checkout
 * - Stay on cart (default): ?add-to-cart=123&redirect=cart
 */
export function useAddToCartFromUrl() {
  const navigate = useNavigate();
  const location = useLocation();
  const { setCart } = useCartStore();
  const processedRef = useRef<Set<string>>(new Set());

  useEffect(() => {
    // Check hash route for add-to-cart parameters
    const hash = window.location.hash;
    const hashParams = new URLSearchParams(hash.split('?')[1] || '');
    const productId = hashParams.get('add-to-cart');

    if (!productId) return;

    const variationId = hashParams.get('variation_id');
    const quantity = parseInt(hashParams.get('quantity') || '1', 10);
    const redirect = hashParams.get('redirect') || 'cart';

    // Create unique key for this add-to-cart request
    const requestKey = `${productId}-${variationId || 'none'}-${quantity}`;

    // Skip if already processed
    if (processedRef.current.has(requestKey)) {
      return;
    }

    // Mark as processed
    processedRef.current.add(requestKey);

    addToCart(productId, variationId, quantity)
      .then((cartData) => {
        // Update cart store with fresh data from API
        if (cartData) {
          setCart(cartData);
        }

        // Remove URL parameters after adding to cart
        const currentPath = window.location.hash.split('?')[0];
        window.location.hash = currentPath;

        // Navigate based on redirect parameter
        const targetPage = redirect === 'checkout' ? '/checkout' : '/cart';
        if (!location.pathname.includes(targetPage)) {
          navigate(targetPage);
        }
      })
      .catch((error) => {
        console.error('[WooNooW] Failed to add product to cart:', error);
        toast.error('Failed to add product to cart');
        // Remove from processed set on error so it can be retried
        processedRef.current.delete(requestKey);
      });
     
  }, [location.hash, location.pathname, navigate, setCart]); // Include all dependencies
}

async function addToCart(
  productId: string,
  variationId: string | null,
  quantity: number
): Promise<any> {
  const apiRoot = (window as any).woonoowCustomer?.apiRoot || '/wp-json/woonoow/v1';
  const nonce = (window as any).woonoowCustomer?.nonce || '';

  const body: any = {
    product_id: parseInt(productId, 10),
    quantity,
  };

  if (variationId) {
    body.variation_id = parseInt(variationId, 10);
  }

  const response = await fetch(`${apiRoot}/cart/add`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-WP-Nonce': nonce,
    },
    credentials: 'include',
    body: JSON.stringify(body),
  });

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(errorData.message || 'Failed to add to cart');
  }

  const data = await response.json();

  // API returns {message, cart_item_key, cart} on success
  if (data.cart_item_key && data.cart) {
    toast.success(data.message || 'Product added to cart');
    return data.cart; // Return cart data to update store
  } else {
    throw new Error(data.message || 'Failed to add to cart');
  }
}
