import React, { useEffect, useState } from 'react';
import { Loader2, AlertCircle } from 'lucide-react';

interface DynamicComponentLoaderProps {
  componentUrl: string;
  moduleId: string;
  fallback?: React.ReactNode;
}

/**
 * Dynamic Component Loader
 * 
 * Loads external React components from addons dynamically
 * The component is loaded as a script and should export a default component
 */
export function DynamicComponentLoader({ 
  componentUrl, 
  moduleId,
  fallback 
}: DynamicComponentLoaderProps) {
  const [Component, setComponent] = useState<React.ComponentType | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let mounted = true;

    const loadComponent = async () => {
      try {
        setLoading(true);
        setError(null);

        // Create a unique global variable name for this component
        const globalName = `WooNooWAddon_${moduleId.replace(/[^a-zA-Z0-9]/g, '_')}`;

        // Check if already loaded
        if ((window as any)[globalName]) {
          if (mounted) {
            setComponent(() => (window as any)[globalName]);
            setLoading(false);
          }
          return;
        }

        // Load the script
        const script = document.createElement('script');
        script.src = componentUrl;
        script.async = true;

        script.onload = () => {
          // The addon script should assign its component to window[globalName]
          const loadedComponent = (window as any)[globalName];
          
          if (!loadedComponent) {
            if (mounted) {
              setError(`Component not found. The addon must export to window.${globalName}`);
              setLoading(false);
            }
            return;
          }

          if (mounted) {
            setComponent(() => loadedComponent);
            setLoading(false);
          }
        };

        script.onerror = () => {
          if (mounted) {
            setError('Failed to load component script');
            setLoading(false);
          }
        };

        document.head.appendChild(script);

        // Cleanup
        return () => {
          mounted = false;
          if (script.parentNode) {
            script.parentNode.removeChild(script);
          }
        };
      } catch (err) {
        if (mounted) {
          setError(err instanceof Error ? err.message : 'Unknown error');
          setLoading(false);
        }
      }
    };

    loadComponent();

    return () => {
      mounted = false;
    };
  }, [componentUrl, moduleId]);

  if (loading) {
    return fallback || (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        <span className="ml-3 text-muted-foreground">Loading component...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-12 text-center">
        <AlertCircle className="h-12 w-12 text-destructive mb-4" />
        <h3 className="text-lg font-semibold mb-2">Failed to Load Component</h3>
        <p className="text-sm text-muted-foreground mb-4">{error}</p>
        <p className="text-xs text-muted-foreground">
          Component URL: <code className="bg-muted px-2 py-1 rounded">{componentUrl}</code>
        </p>
      </div>
    );
  }

  if (!Component) {
    return (
      <div className="flex flex-col items-center justify-center py-12 text-center">
        <AlertCircle className="h-12 w-12 text-muted-foreground mb-4" />
        <p className="text-sm text-muted-foreground">Component not available</p>
      </div>
    );
  }

  return <Component />;
}
