import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
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 { 
  RegisterTenantStep,
  UploadSalesDataStep,
  MLTrainingStep,
  CompletionStep
} from './steps';

interface StepConfig {
  id: string;
  title: string;
  description: string;
  component: React.ComponentType<StepProps>;
}

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

// Steps must match backend ONBOARDING_STEPS exactly
// Note: "user_registered" is auto-completed and not shown in UI
const STEPS: StepConfig[] = [
  {
    id: 'setup',
    title: 'Registrar Panadería',
    description: 'Configura la información básica de tu panadería',
    component: RegisterTenantStep,
  },
  {
    id: 'smart-inventory-setup',
    title: 'Configurar Inventario',
    description: 'Sube datos de ventas y configura tu inventario inicial',
    component: UploadSalesDataStep,
  },
  {
    id: 'ml-training',
    title: 'Entrenamiento IA',
    description: 'Entrena tu modelo de inteligencia artificial personalizado',
    component: MLTrainingStep,
  },
  {
    id: 'completion',
    title: 'Configuración Completa',
    description: '¡Bienvenido a tu sistema de gestión inteligente!',
    component: CompletionStep,
  },
];

export const OnboardingWizard: React.FC = () => {
  const [currentStepIndex, setCurrentStepIndex] = useState(0);
  const [isInitialized, setIsInitialized] = useState(false);
  const navigate = useNavigate();
  const { user } = useAuth();
  
  // Initialize tenant data for authenticated users
  useTenantInitializer();
  
  // Get user progress from backend
  const { data: userProgress, isLoading: isLoadingProgress, error: progressError } = useUserProgress(
    user?.id || '',
    { enabled: !!user?.id }
  );
  
  const markStepCompleted = useMarkStepCompleted();
  const { setCurrentTenant } = useTenantActions();

  // Auto-complete user_registered step if needed (runs first)
  useEffect(() => {
    if (userProgress && user?.id) {
      const userRegisteredStep = userProgress.steps.find(s => s.step_name === 'user_registered');
      
      if (!userRegisteredStep?.completed) {
        console.log('🔄 Auto-completing user_registered step for new user...');
        
        markStepCompleted.mutate({
          userId: user.id,
          stepName: 'user_registered',
          data: { 
            auto_completed: true, 
            completed_at: new Date().toISOString(),
            source: 'onboarding_wizard_auto_completion'
          }
        }, {
          onSuccess: () => {
            console.log('✅ user_registered step auto-completed successfully');
            // The query will automatically refetch and update userProgress
          },
          onError: (error) => {
            console.error('❌ Failed to auto-complete user_registered step:', error);
          }
        });
      }
    }
  }, [userProgress, user?.id, markStepCompleted]);

  // Initialize step index based on backend progress with validation
  useEffect(() => {
    if (userProgress && !isInitialized) {
      console.log('🔄 Initializing onboarding progress:', userProgress);
      
      // Check if user_registered step is completed
      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; // Wait for auto-completion to finish
      }
      
      // Find the current step index based on backend progress
      const currentStepFromBackend = userProgress.current_step;
      let stepIndex = STEPS.findIndex(step => step.id === currentStepFromBackend);
      
      console.log(`🎯 Backend current step: "${currentStepFromBackend}", found at index: ${stepIndex}`);
      
      // If current step is not found (e.g., suppliers step), find the next incomplete step
      if (stepIndex === -1) {
        console.log('🔍 Current step not found in UI steps, finding first incomplete step...');
        
        // Find the first incomplete step that user can access
        for (let i = 0; i < STEPS.length; i++) {
          const step = 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 all visible steps are completed, go to last step
        if (stepIndex === -1) {
          stepIndex = STEPS.length - 1;
          console.log('✅ All steps completed, going to last step');
        }
      }
      
      // Ensure user can't skip ahead - find the first incomplete step
      const firstIncompleteStepIndex = 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} ("${STEPS[stepIndex]?.id}")`);
      
      if (stepIndex !== currentStepIndex) {
        setCurrentStepIndex(stepIndex);
      }
      setIsInitialized(true);
    }
  }, [userProgress, isInitialized, currentStepIndex]);

  const currentStep = STEPS[currentStepIndex];


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

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

    try {
      // Special handling for setup step - set the created tenant in tenant store
      if (currentStep.id === 'setup' && data?.tenant) {
        setCurrentTenant(data.tenant);
      }

      // Mark step as completed in backend
      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}"`);

      // Special handling for smart-inventory-setup: auto-complete suppliers step
      if (currentStep.id === 'smart-inventory-setup' && data?.shouldAutoCompleteSuppliers) {
        try {
          console.log('🔄 Auto-completing suppliers step to enable ML training...');
          await markStepCompleted.mutateAsync({
            userId: user.id,
            stepName: 'suppliers',
            data: {
              auto_completed: true,
              completed_at: new Date().toISOString(),
              source: 'inventory_creation_auto_completion',
              message: 'Suppliers step auto-completed to proceed with ML training'
            }
          });
          console.log('✅ Suppliers step auto-completed successfully');
        } catch (supplierError) {
          console.warn('⚠️ Could not auto-complete suppliers step:', supplierError);
          // Don't fail the entire flow if suppliers step completion fails
        }
      }

      if (currentStep.id === 'completion') {
        navigate('/app');
      } else {
        // Auto-advance to next step after successful completion
        if (currentStepIndex < STEPS.length - 1) {
          setCurrentStepIndex(currentStepIndex + 1);
        }
      }
    } catch (error: any) {
      console.error(`❌ Error completing step "${currentStep.id}":`, error);
      
      // Extract detailed error information
      const errorMessage = error?.response?.data?.detail || error?.message || 'Unknown error';
      const statusCode = error?.response?.status;
      
      console.error(`📊 Error details: Status ${statusCode}, Message: ${errorMessage}`);
      
      // Check if it's a dependency error
      if (errorMessage.includes('dependencies not met')) {
        console.error('🚫 Dependencies not met for step:', currentStep.id);
        
        // Check what dependencies are missing
        if (userProgress) {
          console.log('📋 Current progress:', userProgress);
          console.log('📋 Completed steps:', userProgress.steps.filter(s => s.completed).map(s => s.step_name));
        }
      }
      
      // Don't advance automatically on error - user should see the issue
      alert(`Error al completar paso "${currentStep.title}": ${errorMessage}`);
    }
  };

  // Show loading state while initializing progress
  if (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">Cargando tu progreso...</p>
            </div>
          </CardBody>
        </Card>
      </div>
    );
  }

  // Show error state if progress fails to load
  if (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">
                  Error al cargar progreso
                </h2>
                <p className="text-sm sm:text-base text-[var(--text-secondary)] mb-4 px-2">
                  No pudimos cargar tu progreso de configuración. Puedes continuar desde el inicio.
                </p>
                <Button
                  onClick={() => setIsInitialized(true)}
                  variant="primary"
                  size="lg"
                >
                  Continuar
                </Button>
              </div>
            </div>
          </CardBody>
        </Card>
      </div>
    );
  }

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

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 space-y-4 sm:space-y-6 pb-6">
      {/* Enhanced Progress Header */}
      <Card shadow="sm" padding="lg">
        <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-4 space-y-2 sm:space-y-0">
          <div className="text-center sm:text-left">
            <h1 className="text-xl sm:text-2xl font-bold text-[var(--text-primary)]">
              Bienvenido a Bakery IA
            </h1>
            <p className="text-[var(--text-secondary)] text-xs sm:text-sm mt-1">
              Configura tu sistema de gestión inteligente paso a paso
            </p>
          </div>
          <div className="text-center sm:text-right">
            <div className="text-sm text-[var(--text-secondary)]">
              Paso {currentStepIndex + 1} de {STEPS.length}
            </div>
            <div className="text-xs text-[var(--text-tertiary)]">
              {Math.round(progressPercentage)}% completado
            </div>
          </div>
        </div>
        
        {/* Progress Bar */}
        <div className="w-full bg-[var(--bg-secondary)] rounded-full h-2 sm:h-3 mb-4">
          <div
            className="bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary)]/80 h-2 sm:h-3 rounded-full transition-all duration-500 ease-out"
            style={{ width: `${progressPercentage}%` }}
          />
        </div>

        {/* Mobile Step Indicators - Horizontal scroll on small screens */}
        <div className="sm:hidden">
          <div className="flex space-x-4 overflow-x-auto pb-2 px-1">
            {STEPS.map((step, index) => {
              const isCompleted = userProgress?.steps.find(s => s.step_name === step.id)?.completed || index < currentStepIndex;
              const isCurrent = index === currentStepIndex;
              
              return (
                <div 
                  key={step.id}
                  className={`flex-shrink-0 text-center min-w-[80px] ${
                    isCompleted 
                      ? 'text-[var(--color-success)]' 
                      : isCurrent
                      ? 'text-[var(--color-primary)]'
                      : 'text-[var(--text-tertiary)]'
                  }`}
                >
                  <div className="flex items-center justify-center mb-1">
                    {isCompleted ? (
                      <div className="w-8 h-8 bg-[var(--color-success)] rounded-full flex items-center justify-center shadow-sm">
                        <svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                      </div>
                    ) : isCurrent ? (
                      <div className="w-8 h-8 bg-[var(--color-primary)] rounded-full flex items-center justify-center text-white text-sm font-bold shadow-sm ring-2 ring-[var(--color-primary)]/20">
                        {index + 1}
                      </div>
                    ) : (
                      <div className="w-8 h-8 bg-[var(--bg-tertiary)] rounded-full flex items-center justify-center text-[var(--text-tertiary)] text-sm">
                        {index + 1}
                      </div>
                    )}
                  </div>
                  <div className="text-xs font-medium leading-tight">
                    {step.title}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Desktop Step Indicators */}
        <div className="hidden sm:flex sm:justify-between">
          {STEPS.map((step, index) => {
            const isCompleted = userProgress?.steps.find(s => s.step_name === step.id)?.completed || index < currentStepIndex;
            const isCurrent = index === currentStepIndex;
            
            return (
              <div 
                key={step.id}
                className={`flex-1 text-center px-2 ${
                  isCompleted 
                    ? 'text-[var(--color-success)]' 
                    : isCurrent
                    ? 'text-[var(--color-primary)]'
                    : 'text-[var(--text-tertiary)]'
                }`}
              >
                <div className="flex items-center justify-center mb-2">
                  {isCompleted ? (
                    <div className="w-7 h-7 bg-[var(--color-success)] rounded-full flex items-center justify-center">
                      <svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                    </div>
                  ) : isCurrent ? (
                    <div className="w-7 h-7 bg-[var(--color-primary)] rounded-full flex items-center justify-center text-white text-sm font-bold">
                      {index + 1}
                    </div>
                  ) : (
                    <div className="w-7 h-7 bg-[var(--bg-tertiary)] rounded-full flex items-center justify-center text-[var(--text-tertiary)] text-sm">
                      {index + 1}
                    </div>
                  )}
                </div>
                <div className="text-xs sm:text-sm font-medium mb-1">
                  {step.title}
                </div>
                <div className="text-xs opacity-75">
                  {step.description}
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      {/* Step Content */}
      <Card shadow="lg" padding="none">
        <CardHeader padding="lg" divider>
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-[var(--color-primary)]/10 rounded-full flex items-center justify-center">
              <div className="w-5 h-5 sm:w-6 sm:h-6 bg-[var(--color-primary)] rounded-full flex items-center justify-center text-white text-xs font-bold">
                {currentStepIndex + 1}
              </div>
            </div>
            <div className="flex-1">
              <h2 className="text-lg sm:text-xl font-semibold text-[var(--text-primary)]">
                {currentStep.title}
              </h2>
              <p className="text-[var(--text-secondary)] text-xs sm:text-sm">
                {currentStep.description}
              </p>
            </div>
          </div>
        </CardHeader>
        
        <CardBody padding="lg">
          <StepComponent
            onNext={() => {}} // No-op - steps must use onComplete instead
            onPrevious={() => {}} // No-op - users cannot go back once they've moved forward
            onComplete={handleStepComplete}
            isFirstStep={currentStepIndex === 0}
            isLastStep={currentStepIndex === STEPS.length - 1}
          />
        </CardBody>
      </Card>
    </div>
  );
};