import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '../../ui/Button';
import { Card, CardHeader, CardBody } from '../../ui/Card';
import { useAuth } from '../../../contexts/AuthContext';
import { useUserProgress, useMarkStepCompleted } from '../../../api/hooks/onboarding';
import { useTenantActions } from '../../../stores/tenant.store';
import { useTenantInitializer } from '../../../stores/useTenantInitializer';
import { WizardProvider, useWizardContext, BakeryType, DataSource } from './context';
import {
  BakeryTypeSelectionStep,
  RegisterTenantStep,
  ChildTenantsSetupStep,
  FileUploadStep,
  InventoryReviewStep,
  ProductCategorizationStep,
  InitialStockEntryStep,
  MLTrainingStep,
  CompletionStep
} from './steps';
// Import setup wizard steps
import {
  SuppliersSetupStep,
  InventorySetupStep,
  RecipesSetupStep,
  QualitySetupStep,
  TeamSetupStep,
  ReviewSetupStep,
} from '../setup-wizard/steps';
import { Building2 } from 'lucide-react';

interface StepConfig {
  id: string;
  title: string;
  description: string;
  component: React.ComponentType<any>;
  isConditional?: boolean;
  condition?: (context: any) => boolean;
}

interface StepProps {
  onNext?: () => void;
  onPrevious?: () => void;
  onComplete?: (data?: any) => void;
  onUpdate?: (data?: any) => void;
  isFirstStep?: boolean;
  isLastStep?: boolean;
  initialData?: any;
}

const OnboardingWizardContent: React.FC = () => {
  const { t, i18n } = useTranslation();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { user } = useAuth();
  const wizardContext = useWizardContext();

  // Get subscription tier from localStorage (set during demo/registration)
  const subscriptionTier = localStorage.getItem('subscription_tier') as string;
  const isEnterprise = subscriptionTier === 'enterprise';

  // Fetch user progress early so it's available for step conditions
  const { data: userProgress, isLoading: isLoadingProgress, error: progressError } = useUserProgress(
    user?.id || '',
    { enabled: !!user?.id }
  );

  // Auto-set bakeryType for enterprise users (central baker + retail outlets)
  // Use useEffect to avoid state updates during render
  React.useEffect(() => {
    if (isEnterprise && !wizardContext.state.bakeryType) {
      console.log('🏢 Auto-setting bakeryType to "mixed" for enterprise tier');
      wizardContext.updateBakeryType('mixed'); // Enterprise is always mixed (production + retail)
    }
  }, [isEnterprise, wizardContext.state.bakeryType]);

  // All possible steps with conditional visibility
  // All step IDs match backend ONBOARDING_STEPS exactly
  // Wrapped in useMemo to re-evaluate when language changes
  const ALL_STEPS: StepConfig[] = useMemo(() => [
    // Phase 1: Discovery
    {
      id: 'bakery-type-selection',
      title: t('onboarding:steps.bakery_type.title', 'Tipo de Panadería'),
      description: t('onboarding:steps.bakery_type.description', 'Selecciona tu tipo de negocio'),
      component: BakeryTypeSelectionStep,
      isConditional: true,
      condition: () => {
        // Check localStorage directly to ensure we get the current value
        const currentTier = localStorage.getItem('subscription_tier');
        return currentTier !== 'enterprise'; // Skip for enterprise users
      },
    },
    // Phase 2: Core Setup
    {
      id: 'setup',
      // Dynamic title based on subscription tier
      title: (() => {
        const currentTier = localStorage.getItem('subscription_tier');
        return currentTier === 'enterprise'
          ? t('onboarding:steps.setup.title_enterprise', 'Registrar Obrador Central')
          : t('onboarding:steps.setup.title', 'Registrar Panadería');
      })(),
      description: (() => {
        const currentTier = localStorage.getItem('subscription_tier');
        return currentTier === 'enterprise'
          ? t('onboarding:steps.setup.description_enterprise', 'Información del obrador central')
          : t('onboarding:steps.setup.description', 'Información básica');
      })(),
      component: RegisterTenantStep,
      // No condition - setup step should always be visible
      // The natural flow is: bakery-type-selection → setup
      // Enterprise users skip bakery-type-selection but still need setup
    },
    // Enterprise-specific: Child Tenants Setup
    {
      id: 'child-tenants-setup',
      title: t('onboarding:wizard.steps.child_tenants.title', 'Configurar Sucursales'),
      description: t('onboarding:wizard.steps.child_tenants.description', 'Registra las sucursales de tu red empresarial'),
      component: ChildTenantsSetupStep,
      isConditional: true,
      condition: () => {
        // Check localStorage directly to ensure we get the current value
        const currentTier = localStorage.getItem('subscription_tier');
        return currentTier === 'enterprise'; // Only show for enterprise users
      },
    },
    // POI Detection removed - now happens automatically in background after tenant registration
    // Phase 2a: AI-Assisted Inventory Setup (REFACTORED - split into 3 focused steps)
    {
      id: 'upload-sales-data',
      title: t('onboarding:steps.upload_sales.title', 'Subir Datos de Ventas'),
      description: t('onboarding:steps.upload_sales.description', 'Cargar archivo con historial de ventas'),
      component: FileUploadStep,
      isConditional: true,
      condition: (ctx) => ctx.state.bakeryType !== null, // Tenant created after bakeryType is set
    },
    {
      id: 'inventory-review',
      title: t('onboarding:steps.inventory_review.title', 'Revisar Inventario'),
      description: t('onboarding:steps.inventory_review.description', 'Confirmar productos detectados'),
      component: InventoryReviewStep,
      isConditional: true,
      condition: (ctx) => ctx.state.aiAnalysisComplete,
    },
    {
      id: 'initial-stock-entry',
      title: t('onboarding:steps.stock.title', 'Niveles de Stock'),
      description: t('onboarding:steps.stock.description', 'Cantidades iniciales'),
      component: InitialStockEntryStep,
      isConditional: true,
      // CRITICAL: Check backend completion status to prevent accessing step with only draft data
      // Users can have draft data for inventory-review without completing it,
      // which would populate inventoryItems in context but not mark the step as done in backend
      condition: () => {
        // Check if inventory-review is actually completed in backend
        const inventoryReviewStep = userProgress?.steps?.find(s => s.step_name === 'inventory-review');
        const isBackendComplete = inventoryReviewStep?.completed === true;

        // Also check frontend context for real-time updates during current session
        const isFrontendComplete = wizardContext.state.inventoryReviewCompleted;

        // Require BOTH to be true - this prevents showing step when only draft data exists
        return isBackendComplete && isFrontendComplete;
      },
    },
    {
      id: 'suppliers-setup',
      title: t('onboarding:steps.suppliers.title', 'Proveedores'),
      description: t('onboarding:steps.suppliers.description', 'Configura tus proveedores'),
      component: SuppliersSetupStep,
      // Always show - no conditional
    },
    {
      id: 'inventory-setup',
      title: t('onboarding:steps.inventory.title', 'Inventario'),
      description: t('onboarding:steps.inventory.description', 'Configura tu inventario'),
      component: InventorySetupStep,
      isConditional: true,
      condition: () => false, // Hidden: AI-assisted path is the only active flow
    },
    {
      id: 'recipes-setup',
      title: t('onboarding:steps.recipes.title', 'Recetas'),
      description: t('onboarding:steps.recipes.description', 'Recetas de producción'),
      component: RecipesSetupStep,
      isConditional: true,
      condition: (ctx) =>
        ctx.state.bakeryType === 'production' || ctx.state.bakeryType === 'mixed',
    },
    // Phase 3: Advanced Features (Optional)
    {
      id: 'quality-setup',
      title: t('onboarding:steps.quality.title', 'Calidad'),
      description: t('onboarding:steps.quality.description', 'Estándares de calidad'),
      component: QualitySetupStep,
      isConditional: true,
      condition: (ctx) => ctx.state.bakeryType !== null, // Tenant created after bakeryType is set
    },
    {
      id: 'team-setup',
      title: t('onboarding:steps.team.title', 'Equipo'),
      description: t('onboarding:steps.team.description', 'Miembros del equipo'),
      component: TeamSetupStep,
      isConditional: true,
      condition: (ctx) => ctx.state.bakeryType !== null, // Tenant created after bakeryType is set
    },
    // Phase 4: ML & Finalization
    {
      id: 'ml-training',
      title: t('onboarding:steps.ml_training.title', 'Entrenamiento IA'),
      description: t('onboarding:steps.ml_training.description', 'Modelo personalizado'),
      component: MLTrainingStep,
      // Always show - no conditional
    },
    // Revision step removed - not useful for user, completion step is final step
    {
      id: 'completion',
      title: t('onboarding:steps.completion.title', 'Completado'),
      description: t('onboarding:steps.completion.description', '¡Todo listo!'),
      component: CompletionStep,
    },
  ], [i18n.language, userProgress]); // Re-create steps when language changes or backend data updates

  // Filter visible steps based on wizard context
  // useMemo ensures VISIBLE_STEPS recalculates when wizard context state changes
  // This fixes the bug where conditional steps (suppliers, ml-training) weren't showing
  const VISIBLE_STEPS = useMemo(() => {
    const visibleSteps = ALL_STEPS.filter(step => {
      if (!step.isConditional) return true;
      if (!step.condition) return true;
      return step.condition(wizardContext);
    });

    console.log('🔄 VISIBLE_STEPS recalculated:', visibleSteps.map(s => s.id));
    console.log('📊 Wizard state:', {
      bakeryType: wizardContext.state.bakeryType,
      subscriptionTier: localStorage.getItem('subscription_tier'),
      stockEntryCompleted: wizardContext.state.stockEntryCompleted,
      aiAnalysisComplete: wizardContext.state.aiAnalysisComplete,
      categorizationCompleted: wizardContext.state.categorizationCompleted,
    });

    return visibleSteps;
  }, [ALL_STEPS, wizardContext.state, isEnterprise, userProgress]); // Include userProgress to recalculate when backend data changes

  const isNewTenant = searchParams.get('new') === 'true';
  const [currentStepIndex, setCurrentStepIndex] = useState(0);
  const [isInitialized, setIsInitialized] = useState(isNewTenant);
  const [canContinue, setCanContinue] = useState(true); // Track if current step allows continuation

  useTenantInitializer();

  const markStepCompleted = useMarkStepCompleted();
  const { setCurrentTenant, loadUserTenants } = useTenantActions();
  const [autoCompletionAttempted, setAutoCompletionAttempted] = React.useState(false);

  // Auto-complete user_registered step
  useEffect(() => {
    if (userProgress && user?.id && !autoCompletionAttempted && !markStepCompleted.isPending) {
      const userRegisteredStep = userProgress.steps.find(s => s.step_name === 'user_registered');

      if (!userRegisteredStep?.completed) {
        console.log('🔄 Auto-completing user_registered step for new user...');
        setAutoCompletionAttempted(true);

        const existingData = userRegisteredStep?.data || {};

        markStepCompleted.mutate({
          userId: user.id,
          stepName: 'user_registered',
          data: {
            ...existingData,
            auto_completed: true,
            completed_at: new Date().toISOString(),
            source: 'onboarding_wizard_auto_completion'
          }
        }, {
          onSuccess: () => console.log('✅ user_registered step auto-completed successfully'),
          onError: (error) => {
            console.error('❌ Failed to auto-complete user_registered step:', error);
            setAutoCompletionAttempted(false);
          }
        });
      }
    }
  }, [userProgress, user?.id, autoCompletionAttempted, markStepCompleted.isPending]);

  // Initialize step index based on backend progress
  useEffect(() => {
    if (isNewTenant) return;

    if (userProgress && !isInitialized) {
      console.log('🔄 Initializing onboarding progress:', userProgress);

      const userRegisteredStep = userProgress.steps.find(s => s.step_name === 'user_registered');
      if (!userRegisteredStep?.completed) {
        console.log('⏳ Waiting for user_registered step to be auto-completed...');
        return;
      }

      let stepIndex = 0;

      if (isNewTenant) {
        console.log('🆕 New tenant creation - starting from first step');
        stepIndex = 0;
      } else {
        const currentStepFromBackend = userProgress.current_step;
        stepIndex = VISIBLE_STEPS.findIndex(step => step.id === currentStepFromBackend);

        console.log(`🎯 Backend current step: "${currentStepFromBackend}", found at index: ${stepIndex}`);

        if (stepIndex === -1) {
          for (let i = 0; i < VISIBLE_STEPS.length; i++) {
            const step = VISIBLE_STEPS[i];
            const stepProgress = userProgress.steps.find(s => s.step_name === step.id);

            if (!stepProgress?.completed) {
              stepIndex = i;
              console.log(`📍 Found first incomplete step: "${step.id}" at index ${i}`);
              break;
            }
          }

          if (stepIndex === -1) {
            stepIndex = VISIBLE_STEPS.length - 1;
            console.log('✅ All steps completed, going to last step');
          }
        }

        const firstIncompleteStepIndex = VISIBLE_STEPS.findIndex(step => {
          const stepProgress = userProgress.steps.find(s => s.step_name === step.id);
          return !stepProgress?.completed;
        });

        if (firstIncompleteStepIndex !== -1 && stepIndex > firstIncompleteStepIndex) {
          console.log(`🚫 User trying to skip ahead. Redirecting to first incomplete step at index ${firstIncompleteStepIndex}`);
          stepIndex = firstIncompleteStepIndex;
        }
      }

      console.log(`🎯 Final step index: ${stepIndex} ("${VISIBLE_STEPS[stepIndex]?.id}")`);

      if (stepIndex !== currentStepIndex) {
        setCurrentStepIndex(stepIndex);
      }
      setIsInitialized(true);
    }
  }, [userProgress, isInitialized, currentStepIndex, isNewTenant, VISIBLE_STEPS]);

  const currentStep = VISIBLE_STEPS[currentStepIndex];

  const handleStepComplete = async (data?: any) => {
    if (!user?.id) {
      console.error('User ID not available');
      return;
    }

    // CRITICAL: Guard against undefined currentStep
    if (!currentStep) {
      console.error('❌ Current step is undefined!', {
        currentStepIndex,
        visibleStepsLength: VISIBLE_STEPS.length,
        visibleSteps: VISIBLE_STEPS.map(s => s.id),
        wizardState: wizardContext.state,
      });
      return;
    }

    if (markStepCompleted.isPending) {
      console.warn(`⚠️ Step completion already in progress for "${currentStep.id}", skipping duplicate call`);
      return;
    }

    console.log(`🎯 Completing step: "${currentStep.id}" with data:`, data);

    try {
      // CRITICAL: Mark step as completed in backend FIRST before updating frontend state
      // This ensures backend dependencies are met before we move to dependent steps
      console.log(`📤 Sending API request to complete step: "${currentStep.id}"`);
      await markStepCompleted.mutateAsync({
        userId: user.id,
        stepName: currentStep.id,
        data
      });

      console.log(`✅ Successfully completed step: "${currentStep.id}"`);

      // Update wizard context based on step (AFTER backend confirms completion)
      if (currentStep.id === 'bakery-type-selection' && data?.bakeryType) {
        wizardContext.updateBakeryType(data.bakeryType as BakeryType);
      }
      if (currentStep.id === 'data-source-choice' && data?.dataSource) {
        wizardContext.updateDataSource(data.dataSource as DataSource);
      }
      // REFACTORED: Handle new split steps for AI-assisted inventory
      if (currentStep.id === 'upload-sales-data' && data?.aiSuggestions) {
        wizardContext.updateAISuggestions(data.aiSuggestions);
        wizardContext.updateUploadedFile(data.uploadedFile, data.validationResult);
        wizardContext.setAIAnalysisComplete(true);
      }
      if (currentStep.id === 'inventory-review') {
        wizardContext.markStepComplete('inventoryReviewCompleted');
        // Store inventory items in context for the next step
        if (data?.inventoryItems) {
          wizardContext.updateInventoryItems(data.inventoryItems);
        }
      }
      if (currentStep.id === 'product-categorization' && data?.categorizedProducts) {
        wizardContext.updateCategorizedProducts(data.categorizedProducts);
        wizardContext.markStepComplete('categorizationCompleted');
      }
      if (currentStep.id === 'initial-stock-entry' && data?.productsWithStock) {
        wizardContext.updateProductsWithStock(data.productsWithStock);
        wizardContext.markStepComplete('stockEntryCompleted');
      }
      if (currentStep.id === 'inventory-setup') {
        wizardContext.markStepComplete('inventorySetupCompleted');
      }
      if (currentStep.id === 'setup') {
        console.log('✅ Setup step completed with data:', { hasTenant: !!data?.tenant, hasUser: !!user?.id, data });

        if (data?.tenant) {
          setCurrentTenant(data.tenant);

          // CRITICAL: Reload user tenants to load membership/access information
          // This ensures the user has proper permissions when navigating to dashboard
          if (user?.id) {
            console.log('🔄 [CRITICAL] Reloading user tenants after tenant creation to load access permissions...');
            await loadUserTenants();
            console.log('✅ [CRITICAL] User tenants reloaded successfully');
          } else {
            console.error('❌ [CRITICAL] Cannot reload tenants - user.id is missing!', { user });
          }

          // If tenant info and location are available in data, update the wizard context
          if (data.tenantId && data.bakeryLocation) {
            wizardContext.updateTenantInfo(data.tenantId, data.bakeryLocation);
          }
        } else {
          console.warn('⚠️ Setup step completed but no tenant data provided!');
        }
      }
      if (currentStep.id === 'child-tenants-setup' && data?.childTenants) {
        wizardContext.updateChildTenants(data.childTenants);
        wizardContext.markStepComplete('childTenantsCompleted');

        // Call backend API to create child tenants
        try {
          console.log('🏢 Creating child tenants in backend...');
          const { tenantService } = await import('../../../api');
          const parentTenantId = wizardContext.state.tenantId;

          if (!parentTenantId) {
            console.error('❌ Parent tenant ID not found in wizard context');
            throw new Error('Parent tenant not registered');
          }

          const response = await tenantService.bulkCreateChildTenants(parentTenantId, {
            child_tenants: data.childTenants.map((ct: any) => ({
              name: ct.name,
              city: ct.city,
              zone: ct.zone,
              address: ct.address,
              postal_code: ct.postal_code,
              location_code: ct.location_code,
              latitude: ct.latitude,
              longitude: ct.longitude,
              phone: ct.phone,
              email: ct.email,
              business_type: ct.business_type,
              business_model: ct.business_model,
              timezone: ct.timezone,
              metadata: ct.metadata,
            })),
            auto_configure_distribution: true,
          });

          console.log('✅ Child tenants created successfully:', {
            created: response.created_count,
            failed: response.failed_count,
          });

          if (response.failed_count > 0) {
            console.warn('⚠️ Some child tenants failed to create:', response.failed_tenants);

            // Show specific errors for each failed tenant
            response.failed_tenants.forEach(failed => {
              console.error(`Failed to create tenant ${failed.name} (${failed.location_code}):`, failed.error);
            });
          }
        } catch (childTenantError) {
          console.error('❌ Failed to create child tenants:', childTenantError);
          // Don't block the onboarding flow - log the error and continue
          // The user can add child tenants later from settings
        }
      }

      // Special handling for inventory-review - auto-complete suppliers if requested
      if (currentStep.id === 'inventory-review' && data?.shouldAutoCompleteSuppliers) {
        try {
          console.log('🔄 Auto-completing suppliers-setup step...');
          await markStepCompleted.mutateAsync({
            userId: user.id,
            stepName: 'suppliers-setup',
            data: {
              auto_completed: true,
              completed_at: new Date().toISOString(),
              source: 'inventory_creation_auto_completion',
            }
          });
          console.log('✅ Suppliers-setup step auto-completed successfully');
        } catch (supplierError) {
          console.warn('⚠️ Could not auto-complete suppliers-setup step:', supplierError);
        }
      }

      if (currentStep.id === 'completion') {
        // CRITICAL: Call backend to mark onboarding as fully completed
        if (data?.markFullyCompleted) {
          console.log('🎯 [Completion] Marking onboarding as fully completed in backend...');
          try {
            const { onboardingService } = await import('../../../api');
            await onboardingService.completeOnboarding();
            console.log('✅ [Completion] Onboarding marked as fully completed successfully');
          } catch (error: any) {
            console.error('❌ [Completion] Failed to mark onboarding as fully completed:', error);
            // If completion fails due to conditional steps, it's okay to continue
            // The backend error is logged but we don't block the user
            if (error?.message?.includes('incomplete steps')) {
              console.warn('⚠️ [Completion] Some conditional steps incomplete - this is expected for certain tiers');
            }
          }
        }

        // DON'T reset wizard context here - it breaks VISIBLE_STEPS calculation
        // and causes "can't access property 'component', i is undefined" error
        // The context will be reset when user returns to onboarding flow

        // Don't navigate here - let the CompletionStep handle navigation
        // This prevents double navigation which can cause issues
        if (!data?.redirectTo) {
          navigate(isNewTenant ? '/app/dashboard' : '/app');
        }
      } else {
        if (currentStepIndex < VISIBLE_STEPS.length - 1) {
          setCurrentStepIndex(currentStepIndex + 1);
        }
      }
    } catch (error: any) {
      console.error(`❌ Error completing step "${currentStep.id}":`, error);
      const errorMessage = error?.response?.data?.detail || error?.message || 'Unknown error';
      alert(`${t('onboarding:errors.step_failed', 'Error al completar paso')} "${currentStep.title}": ${errorMessage}`);
    }
  };

  const handleStepUpdate = (data?: any) => {
    // Handle canContinue state updates from setup wizard steps
    if (data?.canContinue !== undefined) {
      setCanContinue(data.canContinue);
    }

    // Handle intermediate updates without marking step complete
    if (currentStep.id === 'bakery-type-selection' && data?.bakeryType) {
      wizardContext.updateBakeryType(data.bakeryType as BakeryType);
    }
    if (currentStep.id === 'data-source-choice' && data?.dataSource) {
      wizardContext.updateDataSource(data.dataSource as DataSource);
    }
    if (currentStep.id === 'product-categorization' && data?.categorizedProducts) {
      wizardContext.updateCategorizedProducts(data.categorizedProducts);
    }
    if (currentStep.id === 'initial-stock-entry' && data?.productsWithStock) {
      wizardContext.updateProductsWithStock(data.productsWithStock);
    }
  };

  const handleGoToPrevious = () => {
    if (currentStepIndex > 0) {
      const previousStep = VISIBLE_STEPS[currentStepIndex - 1];
      console.log(`⬅️  Going back from "${currentStep.id}" to "${previousStep.id}"`);
      setCurrentStepIndex(currentStepIndex - 1);
    } else {
      console.warn('⚠️  Already at first step, cannot go back');
    }
  };

  // Show loading state
  if (!isNewTenant && (isLoadingProgress || !isInitialized)) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6">
        <Card padding="lg" shadow="lg">
          <CardBody>
            <div className="flex items-center justify-center space-x-3">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--color-primary)]"></div>
              <p className="text-[var(--text-secondary)] text-sm sm:text-base">{t('common:loading', 'Cargando tu progreso...')}</p>
            </div>
          </CardBody>
        </Card>
      </div>
    );
  }

  // Show error state
  if (!isNewTenant && progressError) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6">
        <Card padding="lg" shadow="lg">
          <CardBody>
            <div className="text-center space-y-4">
              <div className="w-14 h-14 sm:w-16 sm:h-16 mx-auto bg-[var(--color-error)]/10 rounded-full flex items-center justify-center">
                <svg className="w-7 h-7 sm:w-8 sm:h-8 text-[var(--color-error)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <div>
                <h2 className="text-base sm:text-lg font-semibold text-[var(--text-primary)] mb-2">
                  {t('onboarding:errors.network_error', 'Error al cargar progreso')}
                </h2>
                <p className="text-sm sm:text-base text-[var(--text-secondary)] mb-4 px-2">
                  {t('onboarding:errors.try_again', 'No pudimos cargar tu progreso. Puedes continuar desde el inicio.')}
                </p>
                <Button onClick={() => setIsInitialized(true)} variant="primary" size="lg">
                  {t('onboarding:wizard.navigation.next', 'Continuar')}
                </Button>
              </div>
            </div>
          </CardBody>
        </Card>
      </div>
    );
  }

  // CRITICAL: Guard against undefined currentStep in render
  if (!currentStep) {
    console.error('❌ Cannot render: currentStep is undefined!', {
      currentStepIndex,
      visibleStepsLength: VISIBLE_STEPS.length,
      visibleSteps: VISIBLE_STEPS.map(s => s.id),
      wizardState: wizardContext.state,
    });
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6">
        <Card padding="lg" shadow="lg">
          <CardBody>
            <div className="text-center space-y-4">
              <div className="w-14 h-14 sm:w-16 sm:h-16 mx-auto bg-[var(--color-error)]/10 rounded-full flex items-center justify-center">
                <svg className="w-7 h-7 sm:w-8 sm:h-8 text-[var(--color-error)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <div>
                <h2 className="text-base sm:text-lg font-semibold text-[var(--text-primary)] mb-2">
                  {t('onboarding:errors.step_error', 'Error de configuración')}
                </h2>
                <p className="text-sm sm:text-base text-[var(--text-secondary)] mb-4 px-2">
                  {t('onboarding:errors.step_missing', 'No se pudo cargar el paso actual. Por favor, recarga la página.')}
                </p>
                <Button onClick={() => window.location.reload()} variant="primary" size="lg">
                  {t('common:reload', 'Recargar página')}
                </Button>
              </div>
            </div>
          </CardBody>
        </Card>
      </div>
    );
  }

  const StepComponent = currentStep.component;
  const progressPercentage = isNewTenant
    ? ((currentStepIndex + 1) / VISIBLE_STEPS.length) * 100
    : userProgress?.completion_percentage || ((currentStepIndex + 1) / VISIBLE_STEPS.length) * 100;

  return (
    <div className="max-w-4xl mx-auto px-2 sm:px-4 md:px-6 space-y-4 sm:space-y-5 md:space-y-6 pb-6 md:pb-8">
      {/* Progress Header */}
      <Card shadow="md" padding="lg" className="border border-[var(--border-color)]/50">
        <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-4 sm:mb-5 space-y-3 sm:space-y-0">
          <div className="text-center sm:text-left">
            <h1 className="text-xl sm:text-2xl md:text-3xl font-bold text-[var(--text-primary)]">
              {isNewTenant ? t('onboarding:wizard.title_new', 'Nueva Panadería') : t('onboarding:wizard.title', 'Configuración Inicial')}
            </h1>
            <p className="text-[var(--text-secondary)] text-sm sm:text-base mt-1.5">
              {t('onboarding:wizard.subtitle', 'Configura tu sistema paso a paso')}
            </p>
          </div>
          <div className="text-center sm:text-right bg-[var(--bg-secondary)] rounded-lg px-4 py-3 sm:px-5 sm:py-3.5">
            <div className="text-base sm:text-lg font-semibold text-[var(--text-primary)]">
              {t('onboarding:wizard.progress.step_of', 'Paso {current} de {total}', {
                current: currentStepIndex + 1,
                total: VISIBLE_STEPS.length
              })}
            </div>
            <div className="text-sm text-[var(--text-tertiary)] mt-0.5">
              {Math.round(progressPercentage)}% {t('onboarding:wizard.progress.completed', 'completado')}
            </div>
          </div>
        </div>

        {/* Enhanced Progress Bar with milestone markers */}
        <div className="relative">
          <div className="w-full bg-[var(--bg-secondary)] rounded-full h-3 sm:h-4 shadow-inner">
            <div
              className="bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary)]/90 h-3 sm:h-4 rounded-full transition-all duration-700 ease-out shadow-sm relative overflow-hidden"
              style={{ width: `${progressPercentage}%` }}
            >
              {/* Animated shimmer effect */}
              <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent animate-shimmer"
                style={{
                  backgroundSize: '200% 100%',
                  animation: 'shimmer 2s infinite'
                }}
              />
            </div>
          </div>

          {/* Step milestone indicators */}
          <div className="absolute top-0 left-0 right-0 flex justify-between" style={{ marginTop: '-2px' }}>
            {VISIBLE_STEPS.map((_, index) => {
              const stepProgress = ((index + 1) / VISIBLE_STEPS.length) * 100;
              const isCompleted = stepProgress <= progressPercentage;
              const isCurrent = index === currentStepIndex;

              return (
                <div
                  key={index}
                  className={`w-2 h-2 sm:w-3 sm:h-3 rounded-full transition-all duration-300 ${isCompleted
                      ? 'bg-[var(--color-primary)] ring-2 ring-white shadow-md scale-110'
                      : isCurrent
                        ? 'bg-[var(--color-primary)]/50 ring-2 ring-[var(--color-primary)]/30 animate-pulse'
                        : 'bg-[var(--bg-secondary)] border-2 border-[var(--border-color)]'
                    }`}
                  style={{ marginLeft: index === 0 ? '0' : undefined, marginRight: index === VISIBLE_STEPS.length - 1 ? '0' : undefined }}
                />
              );
            })}
          </div>
        </div>
      </Card>

      {/* Step Content */}
      <Card shadow="xl" padding="none" className="border border-[var(--border-color)]/30 transition-all duration-300">
        <CardHeader padding="lg" divider className="bg-gradient-to-r from-[var(--bg-primary)] to-[var(--bg-secondary)]">
          <div className="flex items-center space-x-3 sm:space-x-4">
            <div className="relative flex-shrink-0">
              <div className="w-12 h-12 sm:w-14 sm:h-14 bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary)]/80 rounded-2xl flex items-center justify-center shadow-lg transform transition-transform duration-300 hover:scale-105">
                <div className="text-white text-lg sm:text-xl font-bold">
                  {currentStepIndex + 1}
                </div>
              </div>
              {/* Decorative ring */}
              <div className="absolute inset-0 rounded-2xl bg-[var(--color-primary)]/20 animate-ping" style={{ animationDuration: '3s' }} />
            </div>
            <div className="flex-1 min-w-0">
              <h2 className="text-xl sm:text-2xl font-bold text-[var(--text-primary)] mb-1">
                {currentStep.title}
              </h2>
              <p className="text-[var(--text-secondary)] text-sm sm:text-base">
                {currentStep.description}
              </p>
            </div>
          </div>
        </CardHeader>

        <CardBody padding="lg" className="bg-[var(--bg-primary)]">
          <StepComponent
            onNext={() => { }}
            onPrevious={handleGoToPrevious}
            onComplete={handleStepComplete}
            onUpdate={handleStepUpdate}
            isFirstStep={currentStepIndex === 0}
            isLastStep={currentStepIndex === VISIBLE_STEPS.length - 1}
            canContinue={canContinue}
            // Pass products directly as prop for InitialStockEntryStep
            {...(currentStep.id === 'initial-stock-entry' && wizardContext.state.inventoryItems
              ? {
                products: wizardContext.state.inventoryItems.map(item => ({
                  id: item.id,
                  name: item.name,
                  type: item.product_type === 'ingredient' ? 'ingredient' : 'finished_product',
                  category: item.category,
                  unit: item.unit_of_measure,
                  initialStock: undefined,
                }))
              }
              : {}
            )}
            initialData={
              // Pass AI data and file to InventoryReviewStep
              currentStep.id === 'inventory-review'
                ? {
                  uploadedFile: wizardContext.state.uploadedFile,
                  validationResult: wizardContext.state.uploadedFileValidation,
                  aiSuggestions: wizardContext.state.aiSuggestions,
                  uploadedFileName: wizardContext.state.uploadedFileName || '',
                  uploadedFileSize: wizardContext.state.uploadedFileSize || 0,
                }
                : undefined
            }
          />
        </CardBody>
      </Card>
    </div>
  );
};

export const UnifiedOnboardingWizard: React.FC = () => {
  const { user } = useAuth();
  const [searchParams] = useSearchParams();
  const isNewTenant = searchParams.get('new') === 'true';

  // Fetch user progress BEFORE rendering WizardProvider
  // This ensures context_state is available to derive initial WizardState
  const { data: userProgress, isLoading: isLoadingProgress } = useUserProgress(
    user?.id || '',
    { enabled: !!user?.id && !isNewTenant }
  );

  // Show loading while fetching progress (for returning users)
  if (!isNewTenant && isLoadingProgress) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6">
        <Card padding="lg" shadow="lg">
          <CardBody>
            <div className="flex items-center justify-center space-x-3">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--color-primary)]"></div>
              <p className="text-[var(--text-secondary)] text-sm sm:text-base">Cargando tu progreso...</p>
            </div>
          </CardBody>
        </Card>
      </div>
    );
  }

  // Pass backend progress to WizardProvider for state restoration
  return (
    <WizardProvider backendProgress={userProgress}>
      <OnboardingWizardContent />
    </WizardProvider>
  );
};

export default UnifiedOnboardingWizard;
