import { useState, useEffect } from 'react';
import MotorStep from './steps/MotorStep';
import PowerSupplyStep from './steps/PowerSupplyStep';
import ColorsStep from './steps/ColorsStep';
import OptionsStep from './steps/OptionsStep';
import RemoteStep from './steps/RemoteStep';
import ToyMountStep from './steps/ToyMountStep';
import BOMSummary from './BOMSummary';

const steps = [
  { id: 'motor', name: 'Motor', component: MotorStep },
  { id: 'powersupply', name: 'Power Supply', component: PowerSupplyStep },
  { id: 'colors', name: 'Colors', component: ColorsStep },
  { id: 'options', name: 'Options', component: OptionsStep },
  { id: 'remote', name: 'Remote', component: RemoteStep },
  { id: 'toymounts', name: 'Toy Mounts', component: ToyMountStep },
  { id: 'summary', name: 'Summary', component: BOMSummary },
];

export default function Wizard({ buildType = 'self-source', initialConfig, updateConfig: updateConfigProp, onBackToMain }) {
  // For RAD Kit, start at Remote step (index 4)
  const getInitialStep = () => {
    if (buildType === 'rad-kit') {
      // Remote step is at index 4 (Motor=0, PowerSupply=1, Colors=2, Options=3, Remote=4, ToyMounts=5, Summary=6)
      return 4;
    }
    return 0;
  };

  const [currentStep, setCurrentStep] = useState(getInitialStep());
  const [config, setConfig] = useState(initialConfig || {
    motor: '57AIM30',
    powerSupply: '24V PSU',
    primaryColor: 'black',
    accentColor: 'black',
    mount: 'Middle Pivot',
    cover: 'Simple',
    standHinge: 'Pivot Plate',
    standFeet: '3030 Extrusion',
    standCrossbarSupports: 'standard',
    pcbMount: null,
  });

  useEffect(() => {
    if (initialConfig) {
      setConfig(initialConfig);
    }
  }, [initialConfig]);

  const updateConfig = (updates) => {
    const newConfig = { ...config, ...updates };
    setConfig(newConfig);
    if (updateConfigProp) {
      updateConfigProp(newConfig);
    }
  };

  // Filter steps for upgrade mode - skip motor and power supply, start with options
  const getFilteredSteps = () => {
    if (buildType === 'upgrade') {
      // For upgrade mode, only show options and summary
      return [
        { id: 'options', name: 'Upgrade Options', component: OptionsStep },
        { id: 'summary', name: 'Summary', component: BOMSummary },
      ];
    }
    return steps;
  };

  const filteredSteps = getFilteredSteps();

  const nextStep = () => {
    // In upgrade mode, no validation needed
    if (buildType === 'upgrade') {
      if (currentStep < filteredSteps.length - 1) {
        setCurrentStep(currentStep + 1);
      }
      return;
    }

    // Validate required selections before moving to next step
    if (currentStep === 0 && !config.motor) {
      // Motor step - require motor selection
      return;
    }
    if (currentStep === 1 && !config.powerSupply) {
      // Power Supply step - require power supply selection
      return;
    }
    
    if (currentStep < filteredSteps.length - 1) {
      setCurrentStep(currentStep + 1);
    }
  };

  const prevStep = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  const canNavigateToStep = (stepIndex) => {
    // Can always go back or stay on current step
    if (stepIndex <= currentStep) {
      return true;
    }
    
    // In upgrade mode, no validation needed
    if (buildType === 'upgrade') {
      return true;
    }
    
    // In RAD Kit mode, all steps are pre-selected, so navigation is always allowed
    if (buildType === 'rad-kit') {
      return true;
    }
    
    // Check if required steps are completed before jumping ahead
    if (stepIndex > 0 && !config.motor) {
      return false; // Can't skip motor step
    }
    if (stepIndex > 1 && !config.powerSupply) {
      return false; // Can't skip power supply step
    }
    
    return true;
  };

  const goToStep = (stepIndex) => {
    if (stepIndex >= 0 && stepIndex < filteredSteps.length && canNavigateToStep(stepIndex)) {
      setCurrentStep(stepIndex);
    }
  };

  const canProceedToNextStep = () => {
    // In upgrade mode, no validation needed
    if (buildType === 'upgrade') {
      return true;
    }
    
    if (currentStep === 0 && !config.motor) {
      return false; // Motor step - require motor selection
    }
    if (currentStep === 1 && !config.powerSupply) {
      return false; // Power Supply step - require power supply selection
    }
    return true;
  };

  const CurrentStepComponent = filteredSteps[currentStep].component;

  // Adjust current step if we're in upgrade mode
  useEffect(() => {
    if (buildType === 'upgrade' && currentStep >= 2) {
      // Skip to options step (index 0 in filtered steps)
      setCurrentStep(0);
    }
  }, [buildType, currentStep]);

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-8">
      <div className="max-w-4xl mx-auto px-4">
        {/* Back Button */}
        {onBackToMain && (
          <div className="mb-4">
            <button
              onClick={onBackToMain}
              className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 font-medium flex items-center gap-2"
            >
              <svg
                className="w-5 h-5"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M10 19l-7-7m0 0l7-7m-7 7h18"
                />
              </svg>
              Back to Main Menu
            </button>
          </div>
        )}

        {/* Header */}
        <div className="mb-8 text-center">
          <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-2">
            OSSM Configurator
          </h1>
          <p className="text-gray-600 dark:text-gray-300">
            {buildType === 'upgrade' 
              ? 'Select upgrade components and modifications'
              : 'Configure your Open Source Sex Machine'}
          </p>
          {buildType === 'upgrade' && (
            <div className="mt-4 bg-purple-50 dark:bg-purple-900/30 border border-purple-200 dark:border-purple-700 rounded-lg p-3 inline-block">
              <p className="text-purple-800 dark:text-purple-300 text-sm font-medium">
                Upgrade Mode: Only modification and upgrade components are shown
              </p>
            </div>
          )}
        </div>

        {/* Step Indicator */}
        <div className="mb-8">
          <div className="flex items-start justify-between relative">
            {filteredSteps.map((step, index) => (
              <div key={step.id} className="flex flex-col items-center flex-1 relative">
                {/* Circle */}
                <button
                  onClick={() => goToStep(index)}
                  className={`w-10 h-10 rounded-full flex items-center justify-center font-semibold flex-shrink-0 z-10 ${
                    index === currentStep
                      ? 'bg-blue-600 dark:bg-blue-500 text-white'
                      : index < currentStep
                      ? 'bg-green-500 dark:bg-green-600 text-white'
                      : 'bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400'
                  } ${
                    index <= currentStep
                      ? 'cursor-pointer hover:opacity-80'
                      : 'cursor-not-allowed'
                  }`}
                  disabled={!canNavigateToStep(index)}
                >
                  {index < currentStep ? '✓' : index + 1}
                </button>
                {/* Connecting line to the right */}
                {index < filteredSteps.length - 1 && (
                  <div
                    className={`absolute top-5 left-1/2 h-1 ${
                      index < currentStep ? 'bg-green-500 dark:bg-green-600' : 'bg-gray-200 dark:bg-gray-700'
                    }`}
                    style={{ 
                      width: 'calc(100% - 40px)',
                      marginLeft: '20px'
                    }}
                  />
                )}
                {/* Text label */}
                <button
                  onClick={() => goToStep(index)}
                  className={`mt-2 text-sm font-medium text-center ${
                    index <= currentStep
                      ? 'text-blue-600 dark:text-blue-400 cursor-pointer hover:text-blue-800 dark:hover:text-blue-300'
                      : 'text-gray-400 dark:text-gray-500 cursor-not-allowed'
                  }`}
                  disabled={!canNavigateToStep(index)}
                >
                  {step.name}
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Step Content */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 md:p-8 mb-6">
          <CurrentStepComponent
            config={config}
            updateConfig={updateConfig}
            nextStep={nextStep}
            prevStep={prevStep}
            buildType={buildType}
          />
        </div>

        {/* Navigation Buttons */}
        {currentStep < filteredSteps.length - 1 && (
          <div className="flex justify-between">
            <button
              onClick={prevStep}
              disabled={currentStep === 0}
              className={`px-6 py-2 rounded-lg font-medium ${
                currentStep === 0
                  ? 'bg-gray-200 dark:bg-gray-700 text-gray-400 dark:text-gray-500 cursor-not-allowed'
                  : 'bg-gray-600 dark:bg-gray-700 text-white hover:bg-gray-700 dark:hover:bg-gray-600'
              }`}
            >
              Previous
            </button>
            <div className="flex gap-2">
              <button
                onClick={nextStep}
                disabled={!canProceedToNextStep()}
                className={`px-6 py-2 rounded-lg font-medium ${
                  canProceedToNextStep()
                    ? 'bg-blue-600 dark:bg-blue-500 text-white hover:bg-blue-700 dark:hover:bg-blue-600'
                    : 'bg-gray-200 dark:bg-gray-700 text-gray-400 dark:text-gray-500 cursor-not-allowed'
                }`}
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
