import { useEffect } from 'react';
import { useEntitlement } from '../hooks/useEntitlement';
import { useLightswitch } from '../hooks/useLightswitch';

/**
 * ProtectedRoute - A route protection component that handles entitlement checks and paywall display
 * 
 * Features:
 * - Automatically checks entitlements on mount
 * - Shows paywall when user is not entitled (regardless of autoShowPaywall setting)
 * - Shows simple loading state while checking
 * - Only shows children when user is entitled
 * 
 * @param {React.ReactNode} children - The protected content to render when entitled
 * @param {string} feature - The feature to check (defaults to "has_access")
 * @param {boolean} showPaywall - Whether to show paywall when not entitled (defaults to true)
 */
const ProtectedRoute = ({ children, feature = "has_access", showPaywall = true }) => {
  const { entitled, loading, error, paywallConfigId, isReady, refresh: refreshEntitlement } = useEntitlement(feature, { checkOnMount: true });
  const { showPaywall: showPaywallFn, isAuthenticated, onPaywallEvent, refreshEntitlements } = useLightswitch();

  // Show paywall when user is not entitled and we have paywall config
  useEffect(() => {
    console.log('ProtectedRoute: Checking paywall conditions:', {
      showPaywall,
      isReady,
      isAuthenticated,
      loading,
      entitled,
      paywallConfigId,
      feature
    });

    if (showPaywall && isReady && isAuthenticated && !loading && !entitled && paywallConfigId) {
      console.log('ProtectedRoute: All conditions met, showing paywall with config:', paywallConfigId);
      
      // Small delay to ensure UI is ready
      setTimeout(async () => {
        try {
          console.log('ProtectedRoute: Calling showPaywallFn...');
          await showPaywallFn({ 
            paywallConfigId: paywallConfigId,
            feature: feature
          });
          console.log('ProtectedRoute: Paywall should now be visible');
        } catch (error) {
          console.error('Error showing paywall from ProtectedRoute:', error);
        }
      }, 500);
    } else {
      console.log('ProtectedRoute: Paywall conditions not met, not showing paywall');
    }
  }, [showPaywall, isReady, isAuthenticated, loading, entitled, paywallConfigId, feature, showPaywallFn]);

  // Listen for paywall success events and refresh entitlements
  useEffect(() => {
    if (!onPaywallEvent) return;

    const unsubscribe = onPaywallEvent((event, _data) => {
      if (event === 'payment_success') {
        console.log('ProtectedRoute: Payment successful, refreshing entitlements...');
        
        // Refresh both the specific feature entitlement and general entitlements
        setTimeout(async () => {
          try {
            await refreshEntitlement();
            await refreshEntitlements();
            console.log('ProtectedRoute: Entitlements refreshed after payment success');
          } catch (error) {
            console.error('Error refreshing entitlements after payment:', error);
          }
        }, 1000); // Small delay to ensure backend has processed the payment
      }
    });

    return unsubscribe;
  }, [onPaywallEvent, refreshEntitlement, refreshEntitlements]);

  // Show content if entitled
  if (entitled) {
    return children;
  }

  // Show loading state while checking entitlements
  if (loading || !isReady) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-300 mx-auto mb-4"></div>
          <p className="text-gray-500">Loading...</p>
        </div>
      </div>
    );
  }

  // Show error state if there's an error
  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-500 mb-2">Access Error</p>
          <p className="text-gray-500 text-sm">{error}</p>
        </div>
      </div>
    );
  }

  // Show access denied state (paywall should be showing at this point)
  return (
    <div className="min-h-screen flex items-center justify-center">
      <div className="text-center">
        <h2 className="text-xl font-semibold text-gray-800 mb-2">Upgrade Required</h2>
        <p className="text-gray-500">This feature requires a subscription to access.</p>
      </div>
    </div>
  );
};

export default ProtectedRoute;
