import React, { useState, useEffect } from 'react';
import { useSetupWizard } from '../SetupWizardContext';
import { ErrorBoundary, InlineErrorFallback } from '../../components/ErrorBoundary';
import { HomebrewSetupStep } from '../steps/HomebrewSetupStep';
import { DockerSetupStep } from '../steps/DockerSetupStep';
import { ArtifactorySetupStep } from '../steps/ArtifactorySetupStep';
import { SshKeysSetupStep } from '../steps/SshKeysSetupStep';
import { InstallInstCliStep } from '../steps/InstallInstCliStep';
import { GerritSetupStep } from '../steps/GerritSetupStep';
import { GitHubSetupStep } from '../steps/GitHubSetupStep';
import { GitSetupStep } from '../steps/GitSetupStep';
import { FrpcSetupStep } from '../steps/FrpcSetupStep';
import { FrpcConfigStep } from '../steps/FrpcConfigStep';
import { GitCloneStep } from '../steps/GitCloneStep';
import { InstCliConfigFileStep } from '../steps/InstCliConfigFileStep';
import { InstCliProxyStep } from '../steps/InstCliProxyStep';
import { BuildRunStep } from '../steps/BuildRunStep';
import { ChromeExtensionStep } from '../steps/ChromeExtensionStep';

const stepComponents: Record<string, React.ComponentType> = {
  HomebrewSetupStep,
  DockerSetupStep,
  ArtifactorySetupStep,
  SshKeysSetupStep,
  InstallInstCliStep,
  GerritSetupStep,
  GitHubSetupStep,
  GitSetupStep,
  FrpcSetupStep,
  FrpcConfigStep,
  GitCloneStep,
  InstCliConfigFileStep,
  InstCliProxyStep,
  BuildRunStep,
  ChromeExtensionStep
};

export const StepContent: React.FC = () => {
  const { steps, currentStepIndex, loading, error, scrollContainerRef } = useSetupWizard();

  // Track which steps have ever been visited so we can keep them mounted.
  const [mountedStepIds, setMountedStepIds] = useState<Set<string>>(new Set());

  useEffect(() => {
    const currentStep = steps[currentStepIndex];
    if (currentStep) {
      setMountedStepIds((prev) => {
        if (prev.has(currentStep.id)) return prev;
        return new Set([...prev, currentStep.id]);
      });
    }
  }, [currentStepIndex, steps]);

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center bg-background">
        <div className="text-center">
          <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-blue-600 border-r-transparent mb-4"></div>
          <p className="text-sm text-muted-foreground">Loading...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex-1 flex items-center justify-center bg-background">
        <div className="text-center text-red-600">
          <p className="text-sm">Error: {error}</p>
        </div>
      </div>
    );
  }

  return (
    <div
      ref={scrollContainerRef}
      className="flex-1 overflow-auto px-6 py-6 bg-background"
    >
      {steps.length === 0 && (
        <div className="flex items-center justify-center h-full">
          <p className="text-sm text-muted-foreground">No step available</p>
        </div>
      )}

      {steps.map((step, index) => {
        // Don't mount until first visited
        if (!mountedStepIds.has(step.id)) return null;

        const StepComponent = stepComponents[step.componentName];
        const isActive = index === currentStepIndex;

        if (!StepComponent) {
          return isActive ? (
            <div key={step.id} className="flex items-center justify-center h-full">
              <p className="text-sm text-red-600">
                Step component not found: {step.componentName}
              </p>
            </div>
          ) : null;
        }

        return (
          // Keep mounted, just hide when not active so component state is preserved
          <div key={step.id} className={isActive ? undefined : 'hidden'}>
            <ErrorBoundary
              fallback={<InlineErrorFallback />}
              onError={(err, errorInfo) => {
                console.error('Step error:', {
                  step: step.id,
                  error: err.message,
                  componentStack: errorInfo.componentStack
                });
              }}
            >
              <StepComponent />
            </ErrorBoundary>
          </div>
        );
      })}
    </div>
  );
};
