import React, { useEffect, useState, useRef } from 'react';
import { loadConnectAndInitialize } from '@stripe/connect-js';

interface StripeEmbeddedOnboardingProps {
  accountId: string;
  clientSecret: string;
  onComplete?: () => void;
  onError?: (error: Error) => void;
}

interface OnboardingStep {
  id: number;
  title: string;
  icon: string;
  status: 'completed' | 'current' | 'pending';
  description: string;
  securityNote: string;
  estimatedTime: string;
}

const onboardingSteps: OnboardingStep[] = [
  {
    id: 1,
    title: "Business Information",
    icon: "🏢",
    status: "current",
    description: "Basic details about your organization",
    securityNote: "All information is encrypted in transit and at rest",
    estimatedTime: "2-3 minutes"
  },
  {
    id: 2,
    title: "Identity Verification",
    icon: "🔐",
    status: "pending",
    description: "Secure verification required by financial regulations",
    securityNote: "Documents are processed by Stripe's secure systems",
    estimatedTime: "5-10 minutes"
  },
  {
    id: 3,
    title: "Bank Account Setup",
    icon: "🏦",
    status: "pending",
    description: "Connect your bank account for automated payouts",
    securityNote: "Bank details are never stored on our servers",
    estimatedTime: "2-3 minutes"
  },
  {
    id: 4,
    title: "Final Review",
    icon: "✅",
    status: "pending",
    description: "Review and complete your secure account setup",
    securityNote: "Your account will be activated immediately",
    estimatedTime: "1-2 minutes"
  }
];

const StripeEmbeddedOnboarding: React.FC<StripeEmbeddedOnboardingProps> = ({
  accountId,
  clientSecret,
  onComplete,
  onError
}) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [_currentStep, setCurrentStep] = useState(1);
  const [steps, setSteps] = useState(onboardingSteps);
  const stripeConnectInstance = useRef<typeof loadConnectAndInitialize | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const initializeStripe = async () => {
      try {
        setLoading(true);
        
        // Initialize Stripe Connect
        const publishableKey = import.meta.env.PUBLIC_STRIPE_PUBLISHABLE_KEY;
        if (!publishableKey) {
          throw new Error('Stripe publishable key not configured');
        }

        stripeConnectInstance.current = loadConnectAndInitialize({
          publishableKey,
          clientSecret,
          appearance: {
            variables: {
              colorPrimary: '#1f2937',
              colorBackground: '#ffffff',
              colorText: '#1f2937',
              colorDanger: '#ef4444',
              fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
              spacingUnit: '4px',
              borderRadius: '8px',
              fontSizeBase: '14px',
              fontWeightNormal: '400',
              fontWeightBold: '600'
            }
          }
        });

        // Create and mount the onboarding component
        const component = stripeConnectInstance.current.create('account-onboarding');
        
        // Set up event listeners before mounting
        component.setOnExit((e: { reason: string }) => {

          if (e.reason === 'account_onboarding_completed') {
            updateStepStatus(4, 'completed');
            onComplete?.();
          } else if (e.reason === 'account_onboarding_closed') {
            // User closed the onboarding flow

          }
        });

        component.setOnLoadError((_e: unknown) => {
          onError?.(new Error('Failed to load onboarding component'));
        });

        // Mount the component
        if (containerRef.current) {
          containerRef.current.appendChild(component);
        }

        setLoading(false);
      } catch (error) {
        // Stripe initialization error
        const errorMessage = error instanceof Error ? error.message : 'Failed to initialize Stripe Connect';
        setError(errorMessage);
        onError?.(error as Error);
        setLoading(false);
      }
    };

    if (accountId && clientSecret) {
      initializeStripe();
    }

    return () => {
      // Cleanup if needed
      if (stripeConnectInstance.current) {
        stripeConnectInstance.current = null;
      }
    };
  }, [accountId, clientSecret, onComplete, onError]);

  const updateStepStatus = (stepId: number, status: 'completed' | 'current' | 'pending') => {
    setSteps(prev => prev.map(step => 
      step.id === stepId ? { ...step, status } : step
    ));
    setCurrentStep(stepId);
  };

  const getStepStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'bg-green-100 border-green-500 text-green-700';
      case 'current':
        return 'bg-blue-100 border-blue-500 text-blue-700';
      case 'pending':
        return 'bg-gray-100 border-gray-300 text-gray-500';
      default:
        return 'bg-gray-100 border-gray-300 text-gray-500';
    }
  };

  const getStepIcon = (status: string) => {
    switch (status) {
      case 'completed':
        return (
          <svg className="w-5 h-5 text-green-600" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
          </svg>
        );
      case 'current':
        return (
          <div className="w-5 h-5 border-2 border-blue-600 rounded-full flex items-center justify-center">
            <div className="w-2 h-2 bg-blue-600 rounded-full animate-pulse"></div>
          </div>
        );
      default:
        return <div className="w-5 h-5 border-2 border-gray-300 rounded-full"></div>;
    }
  };

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="max-w-4xl mx-auto px-6 py-8">
          <div className="bg-white rounded-lg shadow-sm border p-8">
            <div className="text-center">
              <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg className="w-6 h-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                </svg>
              </div>
              <h2 className="text-xl font-semibold text-gray-900 mb-2">Setup Error</h2>
              <p className="text-gray-600 mb-6">{error}</p>
              <div className="space-y-2">
                <button 
                  onClick={() => {
                    setError(null);
                    setLoading(true);
                    window.location.reload();
                  }}
                  className="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-md font-medium transition-colors"
                >
                  Try Again
                </button>
                <a href="/dashboard" className="block w-full bg-gray-600 hover:bg-gray-700 text-white py-2 px-4 rounded-md font-medium transition-colors">
                  Return to Dashboard
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="max-w-4xl mx-auto px-6 py-8">
          <div className="bg-white rounded-lg shadow-sm border p-8">
            <div className="text-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
              <h2 className="text-xl font-semibold text-gray-900 mb-2">Initializing Secure Setup</h2>
              <p className="text-gray-600">Preparing your encrypted onboarding experience...</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Security Header */}
      <header className="bg-gray-900 border-b border-gray-700">
        <div className="max-w-4xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-500 rounded-lg flex items-center justify-center">
                <span className="text-white font-bold text-sm">BCT</span>
              </div>
              <h1 className="text-xl font-semibold text-white">Secure Account Setup</h1>
            </div>
            <div className="flex items-center space-x-4 text-sm text-gray-400">
              <span className="flex items-center">
                <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clipRule="evenodd" />
                </svg>
                256-bit SSL
              </span>
              <span className="text-gray-500">•</span>
              <span>Powered by Stripe</span>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-4xl mx-auto px-6 py-8">
        {/* Progress Steps */}
        <div className="mb-8">
          <div className="bg-white rounded-lg shadow-sm border p-6">
            <div className="mb-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-2">Account Setup Progress</h2>
              <p className="text-sm text-gray-600">Complete each step to activate your payment processing account</p>
            </div>
            
            <div className="space-y-4">
              {steps.map((step, _index) => (
                <div key={step.id} className={`flex items-start p-4 rounded-lg border-2 ${getStepStatusColor(step.status)}`}>
                  <div className="flex-shrink-0 mr-4">
                    {getStepIcon(step.status)}
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-1">
                      <h3 className="font-medium">{step.title}</h3>
                      <span className="text-xs font-medium">{step.estimatedTime}</span>
                    </div>
                    <p className="text-sm mb-2">{step.description}</p>
                    <div className="flex items-center text-xs">
                      <svg className="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                      </svg>
                      {step.securityNote}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Main Onboarding Container */}
        <div className="bg-white rounded-lg shadow-sm border">
          <div className="p-6 border-b border-gray-200">
            <div className="flex items-center justify-center space-x-2 text-sm text-gray-600">
              <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clipRule="evenodd" />
              </svg>
              <span className="text-green-600 font-medium">Secure Connection</span>
              <span className="text-gray-400">•</span>
              <span>Stripe Connect</span>
              <span className="text-gray-400">•</span>
              <span>PCI DSS Compliant</span>
            </div>
          </div>
          
          <div className="p-8">
            <div className="mb-6 text-center">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">Payment Account Setup</h2>
              <p className="text-gray-600 max-w-2xl mx-auto">
                Complete your secure payment processing setup to start accepting payments. 
                All information is encrypted and processed by Stripe's bank-level security infrastructure.
              </p>
            </div>

            {/* Trust Indicators */}
            <div className="mb-8 p-4 bg-blue-50 rounded-lg border border-blue-200">
              <div className="flex items-center justify-center space-x-8 text-sm">
                <div className="flex items-center text-blue-700">
                  <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M2.166 4.999A11.954 11.954 0 0010 1.944 11.954 11.954 0 0017.834 5c.11.65.166 1.32.166 2.001 0 5.225-3.34 9.67-8 11.317C5.34 16.67 2 12.225 2 7c0-.682.057-1.35.166-2.001zm11.541 3.708a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                  </svg>
                  Bank-level Security
                </div>
                <div className="flex items-center text-blue-700">
                  <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                  </svg>
                  PCI DSS Level 1
                </div>
                <div className="flex items-center text-blue-700">
                  <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  Trusted by Millions
                </div>
              </div>
            </div>

            {/* Stripe Embedded Component Container */}
            <div className="stripe-onboarding-container">
              <div ref={containerRef} className="min-h-[400px]" />
            </div>

            {/* Security Footer */}
            <div className="mt-8 pt-6 border-t border-gray-200">
              <div className="text-center text-sm text-gray-500">
                <p className="mb-2">
                  🔒 Your data is protected by industry-leading security measures
                </p>
                <p>
                  Questions? Contact our support team at{' '}
                  <a href="mailto:support@blackcanyontickets.com" className="text-blue-600 hover:text-blue-800">
                    support@blackcanyontickets.com
                  </a>
                </p>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
};

export default StripeEmbeddedOnboarding;