import React, { useState, useEffect } from 'react';
import { Button, Input, Card, Select } from '../../ui';
import { useAuth } from '../../../hooks/api/useAuth';
import { UserRegistration } from '../../../types/auth.types';
import { useToast } from '../../../hooks/ui/useToast';

interface RegisterFormProps {
  onSuccess?: () => void;
  onLoginClick?: () => void;
  className?: string;
  showProgressSteps?: boolean;
}

type RegistrationStep = 'personal' | 'bakery' | 'security' | 'verification';

interface ExtendedUserRegistration {
  // Personal Information
  full_name: string;
  email: string;
  phone: string;
  
  // Bakery Information  
  tenant_name: string;
  bakery_type: string;
  address: string;
  city: string;
  postal_code: string;
  country: string;
  
  // Security
  password: string;
  confirmPassword: string;
  
  // Terms
  acceptTerms: boolean;
  acceptPrivacy: boolean;
  acceptMarketing: boolean;
}

export const RegisterForm: React.FC<RegisterFormProps> = ({
  onSuccess,
  onLoginClick,
  className,
  showProgressSteps = true
}) => {
  const [currentStep, setCurrentStep] = useState<RegistrationStep>('personal');
  const [completedSteps, setCompletedSteps] = useState<Set<RegistrationStep>>(new Set());
  const [isEmailVerificationSent, setIsEmailVerificationSent] = useState(false);
  
  const [formData, setFormData] = useState<ExtendedUserRegistration>({
    full_name: '',
    email: '',
    phone: '',
    tenant_name: '',
    bakery_type: 'traditional',
    address: '',
    city: '',
    postal_code: '',
    country: 'España',
    password: '',
    confirmPassword: '',
    acceptTerms: false,
    acceptPrivacy: false,
    acceptMarketing: false
  });
  
  const [errors, setErrors] = useState<Partial<ExtendedUserRegistration>>({});
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  
  const { register, verifyEmail, isLoading, error } = useAuth();
  const { showToast } = useToast();

  const steps: { id: RegistrationStep; title: string; description: string }[] = [
    { id: 'personal', title: 'Información Personal', description: 'Tus datos básicos' },
    { id: 'bakery', title: 'Tu Panadería', description: 'Detalles del negocio' },
    { id: 'security', title: 'Seguridad', description: 'Contraseña y términos' },
    { id: 'verification', title: 'Verificación', description: 'Confirmar email' }
  ];

  const bakeryTypeOptions = [
    { value: 'traditional', label: 'Panadería Tradicional' },
    { value: 'artisan', label: 'Panadería Artesanal' },
    { value: 'industrial', label: 'Panadería Industrial' },
    { value: 'confectionery', label: 'Pastelería' },
    { value: 'bakery_cafe', label: 'Panadería Cafetería' },
    { value: 'specialty', label: 'Panadería Especializada' },
    { value: 'patisserie', label: 'Pastelería Francesa' },
    { value: 'organic', label: 'Panadería Orgánica' }
  ];

  const validatePersonalStep = (): boolean => {
    const newErrors: Partial<ExtendedUserRegistration> = {};
    
    if (!formData.full_name.trim()) {
      newErrors.full_name = 'El nombre completo es requerido';
    } else if (formData.full_name.trim().length < 2) {
      newErrors.full_name = 'El nombre debe tener al menos 2 caracteres';
    }
    
    if (!formData.email.trim()) {
      newErrors.email = 'El email es requerido';
    } else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(formData.email)) {
      newErrors.email = 'Por favor, ingrese un email válido';
    }
    
    if (!formData.phone.trim()) {
      newErrors.phone = 'El teléfono es requerido';
    } else if (!/^(\+34|0034|34)?[6-9][0-9]{8}$/.test(formData.phone.replace(/\s/g, ''))) {
      newErrors.phone = 'Por favor, ingrese un teléfono español válido (ej: +34 600 000 000)';
    }
    
    setErrors(prev => ({ ...prev, ...newErrors }));
    return Object.keys(newErrors).length === 0;
  };

  const validateBakeryStep = (): boolean => {
    const newErrors: Partial<ExtendedUserRegistration> = {};
    
    if (!formData.tenant_name.trim()) {
      newErrors.tenant_name = 'El nombre de la panadería es requerido';
    } else if (formData.tenant_name.trim().length < 2) {
      newErrors.tenant_name = 'El nombre debe tener al menos 2 caracteres';
    }
    
    if (!formData.address.trim()) {
      newErrors.address = 'La dirección es requerida';
    }
    
    if (!formData.city.trim()) {
      newErrors.city = 'La ciudad es requerida';
    }
    
    if (!formData.postal_code.trim()) {
      newErrors.postal_code = 'El código postal es requerido';
    } else if (!/^[0-5][0-9]{4}$/.test(formData.postal_code)) {
      newErrors.postal_code = 'Por favor, ingrese un código postal español válido (ej: 28001)';
    }
    
    setErrors(prev => ({ ...prev, ...newErrors }));
    return Object.keys(newErrors).length === 0;
  };

  const validateSecurityStep = (): boolean => {
    const newErrors: Partial<ExtendedUserRegistration> = {};
    
    if (!formData.password) {
      newErrors.password = 'La contraseña es requerida';
    } else if (formData.password.length < 8) {
      newErrors.password = 'La contraseña debe tener al menos 8 caracteres';
    } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])?/.test(formData.password)) {
      newErrors.password = 'La contraseña debe contener mayúsculas, minúsculas y números';
    }
    
    if (!formData.confirmPassword) {
      newErrors.confirmPassword = 'Confirma tu contraseña';
    } else if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = 'Las contraseñas no coinciden';
    }
    
    if (!formData.acceptTerms) {
      newErrors.acceptTerms = 'Debes aceptar los términos y condiciones';
    }
    
    if (!formData.acceptPrivacy) {
      newErrors.acceptPrivacy = 'Debes aceptar la política de privacidad';
    }
    
    setErrors(prev => ({ ...prev, ...newErrors }));
    return Object.keys(newErrors).length === 0;
  };

  const handleNextStep = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    
    let isValid = false;
    switch (currentStep) {
      case 'personal':
        isValid = validatePersonalStep();
        break;
      case 'bakery':
        isValid = validateBakeryStep();
        break;
      case 'security':
        isValid = validateSecurityStep();
        break;
      default:
        isValid = true;
    }
    
    if (isValid) {
      setCompletedSteps(prev => new Set([...prev, currentStep]));
      
      const stepOrder: RegistrationStep[] = ['personal', 'bakery', 'security', 'verification'];
      const currentIndex = stepOrder.indexOf(currentStep);
      
      if (currentIndex < stepOrder.length - 1) {
        setCurrentStep(stepOrder[currentIndex + 1]);
        setErrors({}); // Clear errors when moving to next step
      }
      
      // If this is the security step, submit the registration
      if (currentStep === 'security') {
        handleSubmitRegistration();
      }
    }
  };

  const handlePreviousStep = () => {
    const stepOrder: RegistrationStep[] = ['personal', 'bakery', 'security', 'verification'];
    const currentIndex = stepOrder.indexOf(currentStep);
    
    if (currentIndex > 0) {
      setCurrentStep(stepOrder[currentIndex - 1]);
      setErrors({}); // Clear errors when going back
    }
  };

  const handleSubmitRegistration = async () => {
    try {
      const registrationData: UserRegistration = {
        full_name: formData.full_name,
        email: formData.email,
        password: formData.password,
        tenant_name: formData.tenant_name,
        phone: formData.phone
      };
      
      const success = await register(registrationData);
      
      if (success) {
        setIsEmailVerificationSent(true);
        setCurrentStep('verification');
        showToast({
          type: 'success',
          title: 'Cuenta creada exitosamente',
          message: 'Revisa tu email para verificar tu cuenta y completar el registro'
        });
      } else {
        showToast({
          type: 'error',
          title: 'Error al crear la cuenta',
          message: error || 'No se pudo crear la cuenta. Verifica que el email no esté en uso.'
        });
        setCurrentStep('personal'); // Go back to first step to fix issues
      }
    } catch (err) {
      showToast({
        type: 'error',
        title: 'Error de conexión',
        message: 'No se pudo conectar con el servidor. Verifica tu conexión a internet.'
      });
      setCurrentStep('personal');
    }
  };

  const handleInputChange = (field: keyof ExtendedUserRegistration) => (value: string | boolean) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  const getCurrentStepIndex = () => {
    const stepOrder: RegistrationStep[] = ['personal', 'bakery', 'security', 'verification'];
    return stepOrder.indexOf(currentStep);
  };

  const getProgressPercentage = () => {
    return ((getCurrentStepIndex()) / (steps.length - 1)) * 100;
  };

  // Email verification success handler
  const handleEmailVerification = async (token: string) => {
    try {
      const success = await verifyEmail(token);
      if (success) {
        showToast({
          type: 'success',
          title: 'Email verificado exitosamente',
          message: '¡Tu cuenta ha sido activada! Ya puedes iniciar sesión.'
        });
        onSuccess?.();
      } else {
        showToast({
          type: 'error',
          title: 'Error de verificación',
          message: 'El enlace de verificación no es válido o ha expirado'
        });
      }
    } catch (err) {
      showToast({
        type: 'error',
        title: 'Error de conexión',
        message: 'No se pudo verificar el email. Intenta más tarde.'
      });
    }
  };

  return (
    <Card className={`p-8 w-full max-w-4xl ${className || ''}`} role="main">
      <div className="text-center mb-8">
        <h1 className="text-3xl font-bold text-text-primary mb-2">
          Registra tu Panadería
        </h1>
        <p className="text-text-secondary text-lg">
          Crea tu cuenta y comienza a digitalizar tu negocio
        </p>
      </div>

      {/* Progress Indicator */}
      {showProgressSteps && (
        <div className="mb-8">
          <div className="flex items-center justify-between mb-4">
            {steps.map((step, index) => (
              <div 
                key={step.id} 
                className="flex flex-col items-center flex-1"
                role="progressbar"
                aria-valuenow={getCurrentStepIndex() + 1}
                aria-valuemax={steps.length}
                aria-label={`Paso ${index + 1} de ${steps.length}: ${step.title}`}
              >
                <div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold mb-2 transition-all duration-300 ${
                  completedSteps.has(step.id) 
                    ? 'bg-color-success text-white' 
                    : currentStep === step.id 
                      ? 'bg-color-primary text-white ring-4 ring-color-primary/20' 
                      : 'bg-background-secondary text-text-secondary'
                }`}>
                  {completedSteps.has(step.id) ? (
                    <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                  ) : (
                    index + 1
                  )}
                </div>
                <div className="text-center">
                  <div className={`text-xs font-medium ${
                    currentStep === step.id ? 'text-color-primary' : 'text-text-secondary'
                  }`}>
                    {step.title}
                  </div>
                  <div className="text-xs text-text-secondary mt-1">
                    {step.description}
                  </div>
                </div>
                {index < steps.length - 1 && (
                  <div className={`absolute top-5 left-1/2 w-full h-0.5 -z-10 ${
                    completedSteps.has(step.id) ? 'bg-color-success' : 'bg-background-secondary'
                  }`} style={{ marginLeft: '2.5rem' }} />
                )}
              </div>
            ))}
          </div>
          
          {/* Progress Bar */}
          <div className="w-full bg-background-secondary rounded-full h-2">
            <div 
              className="bg-color-primary h-2 rounded-full transition-all duration-500 ease-in-out"
              style={{ width: `${getProgressPercentage()}%` }}
              role="progressbar"
              aria-label="Progreso del registro"
            />
          </div>
        </div>
      )}

      {/* Step Content */}
      {currentStep !== 'verification' ? (
        <form onSubmit={handleNextStep} className="space-y-8">
          {/* Personal Information Step */}
          {currentStep === 'personal' && (
            <div className="space-y-6">
              <div className="text-center mb-6">
                <h2 className="text-xl font-semibold text-text-primary mb-2">
                  Información Personal
                </h2>
                <p className="text-text-secondary">
                  Cuéntanos sobre ti para personalizar tu experiencia
                </p>
              </div>
              
              <div className="grid grid-cols-1 gap-6">
                <Input
                  label="Nombre Completo"
                  placeholder="Juan Pérez García"
                  value={formData.full_name}
                  onChange={handleInputChange('full_name')}
                  error={errors.full_name}
                  disabled={isLoading}
                  required
                  autoComplete="name"
                  leftIcon={
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                    </svg>
                  }
                />
                
                <Input
                  type="email"
                  label="Correo Electrónico"
                  placeholder="tu.email@panaderia.com"
                  value={formData.email}
                  onChange={handleInputChange('email')}
                  error={errors.email}
                  disabled={isLoading}
                  required
                  autoComplete="email"
                  leftIcon={
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
                    </svg>
                  }
                />
                
                <Input
                  type="tel"
                  label="Teléfono"
                  placeholder="+34 600 000 000"
                  value={formData.phone}
                  onChange={handleInputChange('phone')}
                  error={errors.phone}
                  disabled={isLoading}
                  required
                  autoComplete="tel"
                  leftIcon={
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                    </svg>
                  }
                />
              </div>
            </div>
          )}
          {/* Bakery Information Step */}
          {currentStep === 'bakery' && (
            <div className="space-y-6">
              <div className="text-center mb-6">
                <h2 className="text-xl font-semibold text-text-primary mb-2">
                  Información de tu Panadería
                </h2>
                <p className="text-text-secondary">
                  Déjanos conocer los detalles de tu negocio
                </p>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <Input
                  label="Nombre de la Panadería"
                  placeholder="Panadería San José"
                  value={formData.tenant_name}
                  onChange={handleInputChange('tenant_name')}
                  error={errors.tenant_name}
                  disabled={isLoading}
                  required
                  leftIcon={
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                    </svg>
                  }
                />
                
                <Select
                  label="Tipo de Panadería"
                  options={bakeryTypeOptions}
                  value={formData.bakery_type}
                  onChange={handleInputChange('bakery_type')}
                  error={errors.bakery_type}
                  disabled={isLoading}
                  required
                />
              </div>
              
              <Input
                label="Dirección"
                placeholder="Calle Principal 123"
                value={formData.address}
                onChange={handleInputChange('address')}
                error={errors.address}
                disabled={isLoading}
                required
                leftIcon={
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                  </svg>
                }
              />
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <Input
                  label="Ciudad"
                  placeholder="Madrid"
                  value={formData.city}
                  onChange={handleInputChange('city')}
                  error={errors.city}
                  disabled={isLoading}
                  required
                />
                
                <Input
                  label="Código Postal"
                  placeholder="28001"
                  value={formData.postal_code}
                  onChange={handleInputChange('postal_code')}
                  error={errors.postal_code}
                  disabled={isLoading}
                  required
                  maxLength={5}
                />
                
                <Input
                  label="País"
                  value={formData.country}
                  onChange={handleInputChange('country')}
                  disabled={true}
                  required
                />
              </div>
            </div>
          )}

          {/* Security Step */}
          {currentStep === 'security' && (
            <div className="space-y-6">
              <div className="text-center mb-6">
                <h2 className="text-xl font-semibold text-text-primary mb-2">
                  Seguridad y Términos
                </h2>
                <p className="text-text-secondary">
                  Crea una contraseña segura y acepta nuestros términos
                </p>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <Input
                  type={showPassword ? 'text' : 'password'}
                  label="Contraseña"
                  placeholder="Contraseña segura"
                  value={formData.password}
                  onChange={handleInputChange('password')}
                  error={errors.password}
                  disabled={isLoading}
                  autoComplete="new-password"
                  required
                  leftIcon={
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                    </svg>
                  }
                  rightIcon={
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="text-text-secondary hover:text-text-primary"
                      aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
                    >
                      {showPassword ? (
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                        </svg>
                      ) : (
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                      )}
                    </button>
                  }
                />
                
                <Input
                  type={showConfirmPassword ? 'text' : 'password'}
                  label="Confirmar Contraseña"
                  placeholder="Repite tu contraseña"
                  value={formData.confirmPassword}
                  onChange={handleInputChange('confirmPassword')}
                  error={errors.confirmPassword}
                  disabled={isLoading}
                  autoComplete="new-password"
                  required
                  leftIcon={
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  }
                  rightIcon={
                    <button
                      type="button"
                      onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                      className="text-text-secondary hover:text-text-primary"
                      aria-label={showConfirmPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
                    >
                      {showConfirmPassword ? (
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                        </svg>
                      ) : (
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                      )}
                    </button>
                  }
                />
              </div>
              
              <div className="space-y-4 pt-4 border-t border-border-primary">
                <div className="flex items-start space-x-3">
                  <input
                    type="checkbox"
                    id="acceptTerms"
                    checked={formData.acceptTerms}
                    onChange={(e) => handleInputChange('acceptTerms')(e.target.checked)}
                    className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
                    disabled={isLoading}
                  />
                  <label htmlFor="acceptTerms" className="text-sm text-text-secondary cursor-pointer">
                    Acepto los{' '}
                    <a href="#" className="text-color-primary hover:text-color-primary-dark underline">
                      términos y condiciones
                    </a>{' '}
                    de uso
                  </label>
                </div>
                {errors.acceptTerms && (
                  <p className="text-color-error text-sm ml-7">{errors.acceptTerms}</p>
                )}
                
                <div className="flex items-start space-x-3">
                  <input
                    type="checkbox"
                    id="acceptPrivacy"
                    checked={formData.acceptPrivacy}
                    onChange={(e) => handleInputChange('acceptPrivacy')(e.target.checked)}
                    className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
                    disabled={isLoading}
                  />
                  <label htmlFor="acceptPrivacy" className="text-sm text-text-secondary cursor-pointer">
                    Acepto la{' '}
                    <a href="#" className="text-color-primary hover:text-color-primary-dark underline">
                      política de privacidad
                    </a>
                  </label>
                </div>
                {errors.acceptPrivacy && (
                  <p className="text-color-error text-sm ml-7">{errors.acceptPrivacy}</p>
                )}
                
                <div className="flex items-start space-x-3">
                  <input
                    type="checkbox"
                    id="acceptMarketing"
                    checked={formData.acceptMarketing}
                    onChange={(e) => handleInputChange('acceptMarketing')(e.target.checked)}
                    className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
                    disabled={isLoading}
                  />
                  <label htmlFor="acceptMarketing" className="text-sm text-text-secondary cursor-pointer">
                    Deseo recibir información sobre nuevas funcionalidades y ofertas especiales
                    <span className="text-text-tertiary"> (opcional)</span>
                  </label>
                </div>
              </div>
            </div>
          )}

          {/* Navigation Buttons */}
          <div className="flex justify-between pt-6 border-t border-border-primary">
            {currentStep !== 'personal' && (
              <Button
                type="button"
                variant="outline"
                onClick={handlePreviousStep}
                disabled={isLoading}
                className="flex items-center space-x-2"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                </svg>
                <span>Anterior</span>
              </Button>
            )}
            
            <div className="flex-1" />
            
            <Button
              type="submit"
              variant="primary"
              size="lg"
              isLoading={isLoading}
              loadingText={currentStep === 'security' ? 'Creando cuenta...' : 'Procesando...'}
              disabled={isLoading}
              className="flex items-center space-x-2 min-w-[140px]"
            >
              {currentStep === 'security' ? (
                <>
                  <span>Crear Cuenta</span>
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </>
              ) : (
                <>
                  <span>Continuar</span>
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </>
              )}
            </Button>
          </div>

          {error && (
            <div className="bg-color-error/10 border border-color-error/20 text-color-error px-4 py-3 rounded-lg text-sm flex items-start space-x-3" role="alert">
              <svg className="w-5 h-5 mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
              </svg>
              <span>{error}</span>
            </div>
          )}
        </form>
      ) : (
        /* Verification Step */
        <div className="text-center space-y-6">
          <div className="w-20 h-20 bg-color-success/10 rounded-full flex items-center justify-center mx-auto mb-6">
            <svg className="w-10 h-10 text-color-success" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
            </svg>
          </div>
          
          <h2 className="text-2xl font-bold text-text-primary mb-4">
            ¡Cuenta creada exitosamente!
          </h2>
          
          <div className="bg-background-secondary rounded-lg p-6 max-w-md mx-auto">
            <p className="text-text-secondary mb-4">
              Hemos enviado un enlace de verificación a:
            </p>
            <p className="text-text-primary font-semibold text-lg mb-4">
              {formData.email}
            </p>
            <p className="text-text-secondary text-sm">
              Revisa tu bandeja de entrada (y la carpeta de spam) y haz clic en el enlace para activar tu cuenta.
            </p>
          </div>
          
          <div className="space-y-4 max-w-md mx-auto">
            <Button
              variant="outline"
              onClick={() => {
                setCurrentStep('personal');
                setIsEmailVerificationSent(false);
                setFormData({
                  full_name: '',
                  email: '',
                  phone: '',
                  tenant_name: '',
                  bakery_type: 'traditional',
                  address: '',
                  city: '',
                  postal_code: '',
                  country: 'España',
                  password: '',
                  confirmPassword: '',
                  acceptTerms: false,
                  acceptPrivacy: false,
                  acceptMarketing: false
                });
                setErrors({});
                setCompletedSteps(new Set());
              }}
              className="w-full"
            >
              Registrar otra cuenta
            </Button>
          </div>
        </div>
      )}

      {/* Login Link */}
      {onLoginClick && currentStep !== 'verification' && (
        <div className="mt-8 text-center border-t border-border-primary pt-6">
          <p className="text-text-secondary mb-4">
            ¿Ya tienes una cuenta?
          </p>
          <Button
            variant="ghost"
            onClick={onLoginClick}
            disabled={isLoading}
            className="text-color-primary hover:text-color-primary-dark"
          >
            Iniciar Sesión
          </Button>
        </div>
      )}
    </Card>
  );
};

export default RegisterForm;