import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { OnboardingWizard, OnboardingStep } from '../../../components/domain/onboarding/OnboardingWizard';
import { useOnboarding } from '../../../hooks/business/onboarding';
import { useAuthUser, useIsAuthenticated } from '../../../stores/auth.store';
import { LoadingSpinner } from '../../../components/shared/LoadingSpinner';

// Step Components
import { BakerySetupStep } from '../../../components/domain/onboarding/steps/BakerySetupStep';
import { DataProcessingStep } from '../../../components/domain/onboarding/steps/DataProcessingStep';
import { ReviewStep } from '../../../components/domain/onboarding/steps/ReviewStep';
import { InventorySetupStep } from '../../../components/domain/onboarding/steps/InventorySetupStep';
import { SuppliersStep } from '../../../components/domain/onboarding/steps/SuppliersStep';
import { MLTrainingStep } from '../../../components/domain/onboarding/steps/MLTrainingStep';
import { CompletionStep } from '../../../components/domain/onboarding/steps/CompletionStep';

const OnboardingPage: React.FC = () => {
  const navigate = useNavigate();
  const user = useAuthUser();
  const isAuthenticated = useIsAuthenticated();
  
  // Use the onboarding business hook
  const {
    currentStep,
    steps,
    data,
    isLoading,
    error,
    nextStep,
    previousStep,
    goToStep,
    updateStepData,
    validateCurrentStep,
    createTenant,
    processSalesFile,
    generateInventorySuggestions,
    createInventoryFromSuggestions,
    completeOnboarding,
    clearError,
    reset
  } = useOnboarding();

  // Map steps to components
  const stepComponents: { [key: string]: React.ComponentType<any> } = {
    'setup': BakerySetupStep,
    'data-processing': DataProcessingStep,
    'review': ReviewStep,
    'inventory': InventorySetupStep,
    'suppliers': SuppliersStep,
    'ml-training': MLTrainingStep,
    'completion': CompletionStep
  };

  // Convert hook steps to OnboardingWizard format
  const wizardSteps: OnboardingStep[] = steps.map(step => ({
    id: step.id,
    title: step.title,
    description: step.description,
    component: stepComponents[step.id],
    isRequired: step.isRequired,
    validation: step.validation
  }));

  const handleStepChange = (stepIndex: number, stepData: any) => {
    const stepId = steps[stepIndex]?.id;
    if (stepId) {
      updateStepData(stepId, stepData);
    }
  };

  const handleNext = () => {
    return nextStep();
  };

  const handlePrevious = () => {
    return previousStep();
  };

  const handleComplete = async (allData: any) => {
    const success = await completeOnboarding();
    if (success) {
      // Navigation is handled inside completeOnboarding
      return;
    }
  };

  // Redirect if user is not authenticated
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/auth/login');
    }
  }, [isAuthenticated, navigate]);

  // Clear error when user navigates away
  useEffect(() => {
    return () => {
      if (error) {
        clearError();
      }
    };
  }, [error, clearError]);

  // Show loading while processing
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <LoadingSpinner size="lg" message="Procesando..." />
      </div>
    );
  }

  // Show error state
  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-xl font-semibold text-red-600 mb-4">Error en Onboarding</h2>
          <p className="text-gray-600 mb-4">{error}</p>
          <div className="space-x-4">
            <button
              onClick={clearError}
              className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
            >
              Reintentar
            </button>
            <button
              onClick={reset}
              className="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
            >
              Reiniciar
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <OnboardingWizard
        steps={wizardSteps}
        currentStep={currentStep}
        data={data}
        onStepChange={handleStepChange}
        onNext={handleNext}
        onPrevious={handlePrevious}
        onComplete={handleComplete}
        onGoToStep={goToStep}
      />
    </div>
  );
};

export default OnboardingPage;