import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button, Input, Card } from '../../components/ui';
import { useRequestPasswordReset } from '../../api/hooks/auth';
import { showToast } from '../../utils/toast';
import { validateEmail } from '../../utils/validation';
import { PublicLayout } from '../../components/layout';

const ForgotPasswordPage: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [email, setEmail] = useState('');
  const [errors, setErrors] = useState<{ email?: string }>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);

  const { mutate: requestPasswordReset } = useRequestPasswordReset({
    onSuccess: () => {
      showToast.success(
        'Si una cuenta con este email existe, recibirás un enlace de recuperación.',
        { title: 'Instrucciones enviadas' }
      );
      setIsSubmitted(true);
    },
    onError: (error: any) => {
      const errorMessage = error.response?.data?.detail || 
                          'Hubo un problema al enviar las instrucciones de recuperación.';
      showToast.error(errorMessage, { title: 'Error' });
    },
    onSettled: () => {
      setIsSubmitting(false);
    }
  });

  const validateForm = (): boolean => {
    const newErrors: { email?: string } = {};

    const emailValidation = validateEmail(email);
    if (!emailValidation.isValid) {
      newErrors.email = t('auth:validation.email_invalid', 'Por favor, ingrese un email válido');
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);
    requestPasswordReset(email);
  };

  const handleGoBackToLogin = () => {
    navigate('/login');
  };

  if (isSubmitted) {
    return (
      <PublicLayout
        variant="centered"
        maxWidth="md"
        headerProps={{
          showThemeToggle: true,
          showAuthButtons: false,
          showLanguageSelector: true,
          variant: "minimal"
        }}
      >
        <Card className="p-8 w-full max-w-md mx-auto" role="main">
          <div className="text-center mb-8">
            <div className="mx-auto bg-color-success/10 p-3 rounded-full w-16 h-16 flex items-center justify-center mb-4">
              <svg
                className="w-8 h-8 text-color-success"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                aria-hidden="true"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h1 className="text-2xl font-bold text-text-primary mb-2">
              {t('auth:forgot_password.submitted_title', '¡Instrucciones Enviadas!')}
            </h1>
            <p className="text-text-secondary">
              {t('auth:forgot_password.submitted_message', 'Hemos enviado un enlace de recuperación a tu correo electrónico.')}
            </p>
          </div>

          <div className="space-y-4">
            <Button
              variant="primary"
              size="lg"
              isFullWidth
              onClick={handleGoBackToLogin}
              className="mt-4"
            >
              Volver al Inicio de Sesión
            </Button>
          </div>
        </Card>
      </PublicLayout>
    );
  }

  return (
    <PublicLayout
      variant="centered"
      maxWidth="md"
      headerProps={{
        showThemeToggle: true,
        showAuthButtons: false,
        showLanguageSelector: true,
        variant: "minimal"
      }}
    >
      <Card className="p-8 w-full max-w-md mx-auto" role="main">
        <div className="text-center mb-8">
          <h1 className="text-2xl font-bold text-text-primary mb-2">
            {t('auth:forgot_password.title', '¿Olvidaste tu contraseña?')}
          </h1>
          <p className="text-text-secondary">
            {t('auth:forgot_password.subtitle', 'Ingresa tu correo electrónico y te enviaremos un enlace para restablecer tu contraseña.')}
          </p>
        </div>

        <form
          onSubmit={handleSubmit}
          className="space-y-6"
          noValidate
          aria-label={t('auth:forgot_password.title', 'Formulario de recuperación de contraseña')}
        >
          <div>
            <Input
              type="email"
              label={t('auth:login.email', 'Correo Electrónico')}
              placeholder="tu.email@panaderia.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              error={errors.email}
              disabled={isSubmitting}
              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>

          <Button
            type="submit"
            variant="primary"
            size="lg"
            isFullWidth
            isLoading={isSubmitting}
            loadingText="Enviando instrucciones..."
            disabled={isSubmitting}
          >
            {isSubmitting ? 'Enviando...' : 'Enviar Instrucciones'}
          </Button>
        </form>

        <div className="mt-6 text-center">
          <button
            type="button"
            onClick={handleGoBackToLogin}
            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"
          >
            ← Volver al Inicio de Sesión
          </button>
        </div>
      </Card>
    </PublicLayout>
  );
};

export default ForgotPasswordPage;