import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api/client';

interface WooCommerceHooksProps {
  context: 'product' | 'shop' | 'cart' | 'checkout';
  hookName: string;
  productId?: number;
  className?: string;
}

/**
 * WooCommerce Hook Bridge Component
 * Renders content from WooCommerce action hooks
 * Allows compatibility with WooCommerce plugins
 */
export function WooCommerceHooks({ context, hookName, productId, className }: WooCommerceHooksProps) {
  const { data, isLoading } = useQuery({
    queryKey: ['wc-hooks', context, productId],
    queryFn: async () => {
      const params: Record<string, any> = {};
      if (productId) {
        params.product_id = productId;
      }
      
      const response = await apiClient.get<{
        success: boolean;
        context: string;
        hooks: Record<string, string>;
      }>(`/hooks/${context}`, params);
      
      return response;
    },
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  if (isLoading || !data?.hooks?.[hookName]) {
    return null;
  }

  return (
    <div
      className={className}
      dangerouslySetInnerHTML={{ __html: data.hooks[hookName] }}
    />
  );
}

/**
 * Hook to get all hooks for a context
 */
function useWooCommerceHooks(context: 'product' | 'shop' | 'cart' | 'checkout', productId?: number) {
  return useQuery({
    queryKey: ['wc-hooks', context, productId],
    queryFn: async () => {
      const params: Record<string, any> = {};
      if (productId) {
        params.product_id = productId;
      }
      
      const response = await apiClient.get<{
        success: boolean;
        context: string;
        hooks: Record<string, string>;
      }>(`/hooks/${context}`, params);
      
      return response.hooks || {};
    },
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Render multiple hooks in sequence
 */
interface HookSequenceProps {
  context: 'product' | 'shop' | 'cart' | 'checkout';
  hooks: string[];
  productId?: number;
  className?: string;
}

export function HookSequence({ context, hooks, productId, className }: HookSequenceProps) {
  const { data: allHooks } = useWooCommerceHooks(context, productId);

  if (!allHooks) {
    return null;
  }

  return (
    <>
      {hooks.map((hookName) => {
        const content = allHooks[hookName];
        if (!content) return null;

        return (
          <div
            key={hookName}
            className={className}
            data-hook={hookName}
            dangerouslySetInnerHTML={{ __html: content }}
          />
        );
      })}
    </>
  );
}
