import React, { useState, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Input, Card } from '../../ui';
import { useAuthActions, useAuthLoading, useAuthError } from '../../../stores/auth.store';
import { showToast } from '../../../utils/toast';
import { validateEmail } from '../../../utils/validation';

interface LoginFormProps {
  onSuccess?: () => void;
  onRegisterClick?: () => void;
  onForgotPasswordClick?: () => void;
  className?: string;
  autoFocus?: boolean;
}

interface LoginCredentials {
  email: string;
  password: string;
  remember_me: boolean;
}

export const LoginForm: React.FC<LoginFormProps> = ({
  onSuccess,
  onRegisterClick,
  onForgotPasswordClick,
  className,
  autoFocus = true
}) => {
  const { t } = useTranslation();
  const [credentials, setCredentials] = useState<LoginCredentials>({
    email: '',
    password: '',
    remember_me: false
  });
  const [errors, setErrors] = useState<Partial<LoginCredentials>>({});
  const [showPassword, setShowPassword] = useState(false);
  const emailInputRef = useRef<HTMLInputElement>(null);

  const { login } = useAuthActions();
  const isLoading = useAuthLoading();
  const error = useAuthError();
  

  // Auto-focus on email field when component mounts
  useEffect(() => {
    if (autoFocus && emailInputRef.current) {
      emailInputRef.current.focus();
    }
  }, [autoFocus]);

  const validateForm = (): boolean => {
    const newErrors: Partial<LoginCredentials> = {};
    
    const emailValidation = validateEmail(credentials.email);
    if (!emailValidation.isValid) {
      newErrors.email = t('auth:validation.email_invalid', emailValidation.error || 'Por favor, ingrese un email válido');
    }
    
    if (!credentials.password) {
      newErrors.password = t('auth:validation.password_required', 'La contraseña es requerida');
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      // Focus on first error field
      const firstErrorField = Object.keys(errors)[0];
      if (firstErrorField === 'email' && emailInputRef.current) {
        emailInputRef.current.focus();
      }
      return;
    }

    try {
      await login(credentials.email, credentials.password);
      showToast.success('¡Bienvenido de vuelta a tu panadería!', {
        title: 'Sesión iniciada correctamente'
      });
      onSuccess?.();
    } catch (err) {
      showToast.error(error || 'Email o contraseña incorrectos. Verifica tus credenciales.', {
        title: 'Error al iniciar sesión'
      });
    }
  };

  const handleInputChange = (field: keyof LoginCredentials) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setCredentials(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !isLoading) {
      handleSubmit(e as any);
    }
  };

  return (
    <Card className={`p-8 w-full max-w-md ${className || ''}`} role="main">
      <div className="text-center mb-8">
        <h1 className="text-2xl font-bold text-text-primary mb-2">
          {t('auth:login.title', 'Iniciar Sesión')}
        </h1>
        <p className="text-text-secondary">
          {t('auth:login.subtitle', 'Accede al panel de control de tu panadería')}
        </p>
      </div>

      <form 
        onSubmit={handleSubmit} 
        className="space-y-6"
        noValidate
        aria-label={t('auth:login.title', 'Formulario de inicio de sesión')}
        onKeyDown={handleKeyDown}
      >
        <div>
          <Input
            ref={emailInputRef}
            type="email"
            label={t('auth:login.email', 'Correo Electrónico')}
            placeholder="tu.email@panaderia.com"
            value={credentials.email}
            onChange={handleInputChange('email')}
            error={errors.email}
            disabled={isLoading}
            autoComplete="email"
            required
            aria-describedby={errors.email ? 'email-error' : undefined}
            leftIcon={
              <svg 
                className="w-5 h-5" 
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
                aria-hidden="true"
              >
                <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>
            }
          />
          {errors.email && (
            <p id="email-error" className="text-color-error text-sm mt-1" role="alert">
              {errors.email}
            </p>
          )}
        </div>

        <div>
          <Input
            type={showPassword ? 'text' : 'password'}
            label={t('auth:login.password', 'Contraseña')}
            placeholder={t('auth:login.password', 'Tu contraseña segura')}
            value={credentials.password}
            onChange={handleInputChange('password')}
            error={errors.password}
            disabled={isLoading}
            autoComplete="current-password"
            required
            aria-describedby={errors.password ? 'password-error' : undefined}
            leftIcon={
              <svg 
                className="w-5 h-5" 
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
                aria-hidden="true"
              >
                <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 transition-colors"
                aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
                tabIndex={0}
              >
                {showPassword ? (
                  <svg 
                    className="w-5 h-5" 
                    fill="none" 
                    stroke="currentColor" 
                    viewBox="0 0 24 24"
                    aria-hidden="true"
                  >
                    <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"
                    aria-hidden="true"
                  >
                    <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>
            }
          />
          {errors.password && (
            <p id="password-error" className="text-color-error text-sm mt-1" role="alert">
              {errors.password}
            </p>
          )}
        </div>

        <div className="flex items-center justify-between">
          <label className="flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={credentials.remember_me}
              onChange={handleInputChange('remember_me')}
              className="rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0 h-4 w-4"
              disabled={isLoading}
              aria-describedby="remember-me-description"
            />
            <span className="ml-2 text-sm text-text-secondary select-none">
              Mantener sesión iniciada
            </span>
          </label>
          
          {onForgotPasswordClick && (
            <button
              type="button"
              onClick={onForgotPasswordClick}
              className="text-sm text-color-primary hover:text-color-primary-dark transition-colors underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-color-primary focus:ring-offset-2 rounded"
              disabled={isLoading}
            >
              ¿Olvidaste tu contraseña?
            </button>
          )}
        </div>

        <div id="remember-me-description" className="sr-only">
          Al activar esta opción, tu sesión permanecerá activa durante más tiempo
        </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"
            aria-live="polite"
          >
            <svg 
              className="w-5 h-5 mt-0.5 flex-shrink-0" 
              fill="currentColor" 
              viewBox="0 0 20 20"
              aria-hidden="true"
            >
              <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>
        )}

        <Button
          type="submit"
          variant="primary"
          size="lg"
          isFullWidth
          isLoading={isLoading}
          loadingText="Verificando credenciales..."
          disabled={isLoading}
          aria-describedby="login-button-description"
        >
          {isLoading ? 'Iniciando sesión...' : 'Acceder a mi Panadería'}
        </Button>

        <div id="login-button-description" className="sr-only">
          Presiona Enter o haz clic para iniciar sesión con tus credenciales
        </div>
      </form>

      {onRegisterClick && (
        <div className="mt-8 text-center border-t border-border-primary pt-6">
          <p className="text-text-secondary mb-4">
            ¿Aún no tienes una cuenta para tu panadería?
          </p>
          <Button
            variant="outline"
            onClick={onRegisterClick}
            disabled={isLoading}
            className="focus:outline-none focus:ring-2 focus:ring-color-primary focus:ring-offset-2"
          >
            Registrar mi Panadería
          </Button>
        </div>
      )}
    </Card>
  );
};

export default LoginForm;