import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '../../Atoms/Button/Button';
import { Typography } from '../../Atoms/Typography/Typography';
import { Icon } from '../../Atoms/Icon/Icon';
import { FONT_FAMILY_SANS, FONT_FAMILY_MONO } from '../../../designTokens';

export const ForgotPassword = ({
  onBackToLogin,
  onSubmit,
  loading: externalLoading,
  error: externalError,
  className = '',
  variant = 'default',
  layout = 'embedded',
  ...props
}) => {
  const { t } = useTranslation();
  const isHexaLogin = variant === 'hexa-login';
  const isPageLayout = layout === 'page';

  // Estados internos (si no se pasan como props)
  const [email, setEmail] = useState('');
  const [errors, setErrors] = useState({});
  const [internalLoading, setInternalLoading] = useState(false);
  const [resetLink, setResetLink] = useState(null);
  const [internalError, setInternalError] = useState(null);
  const [isEmailFocused, setIsEmailFocused] = useState(false);

  // Usar loading externo o interno
  const loading = externalLoading !== undefined ? externalLoading : internalLoading;
  // Usar error externo o interno
  const error = externalError !== undefined ? externalError : internalError;

  // Funciones de validación
  const hasAtSymbol = (email) => {
    return email && email.includes('@');
  };

  const isValidEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const validateForm = () => {
    const newErrors = {};

    if (!email) {
      newErrors.email = t('errors.required') ?? 'Este campo es obligatorio';
    } else if (!isValidEmail(email)) {
      newErrors.email = t('errors.invalidEmail') ?? 'El mail ingresado no es válido';
    }

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

  const handleEmailChange = (e) => {
    const value = e.target.value;
    setEmail(value);

    // Limpiar errores al cambiar
    if (errors.email) {
      setErrors((prev) => ({ ...prev, email: null }));
    }
    // Si hay error interno, limpiarlo
    if (internalError) {
      setInternalError(null);
    }
    // Si hay error externo, no lo manejamos aquí (el componente padre debe manejarlo)
  };

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

    if (!validateForm()) {
      return;
    }

    if (!onSubmit) {
      console.warn('ForgotPassword: onSubmit prop is required');
      return;
    }

    // Usar loading interno si no se pasa como prop
    if (externalLoading === undefined) {
      setInternalLoading(true);
    }
    setErrors({});
    setInternalError(null);

    try {
      const result = await onSubmit({ email, countryCode: null });
      
      if (result?.resetLink) {
        setResetLink(result.resetLink);
      } else {
        // Si no hay resetLink pero no hay error, asumir éxito
        setResetLink('success');
      }
    } catch (err) {
      let errorMessage = t('forgotPassword.errors.sendFailed') ?? 'Error al enviar el link. Intenta nuevamente.';

      if (err?.response?.status === 404) {
        errorMessage = err?.response?.data?.message || 
          err?.message || 
          'No se encontró una cuenta asociada a este correo electrónico. Por favor, verifica que el correo esté correcto.';
      } else if (err?.response?.status === 400) {
        errorMessage = err?.response?.data?.message || 
          err?.message || 
          'El correo electrónico ingresado no es válido.';
      } else if (err?.response?.status >= 500) {
        errorMessage = 'Error del servidor. Por favor, intenta más tarde.';
      } else if (err?.message) {
        errorMessage = err.message;
      }

      if (externalError === undefined) {
        setInternalError(errorMessage);
      }
      // Si el error viene como prop, el componente padre lo maneja
    } finally {
      if (externalLoading === undefined) {
        setInternalLoading(false);
      }
    }
  };

  return (
    <div
      className={`${isPageLayout ? 'min-h-screen flex flex-col' : ''} ${className}`}
      style={isPageLayout ? { backgroundColor: '#f5f5f5' } : undefined}
      data-variant={isHexaLogin ? 'hexa-login' : undefined}
      data-layout={layout}
      {...props}
    >
      <div className={isPageLayout ? 'flex-1 flex items-center justify-center p-4' : 'p-4'}>
        <div className="w-full max-w-md">
          {/* Título y subtítulo */}
          <div className="mb-8 text-center">
            <Typography
              variant="h3"
              className="mb-2 font-semibold"
              style={{
                color: '#2D5C63',
                fontFamily: 'inherit',
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: '32px',
                lineHeight: '48px',
                letterSpacing: '0px',
                textAlign: 'center',
              }}
            >
              {t('forgotPassword.title') ?? 'Recuperar contraseña'}
            </Typography>
            <Typography
              variant="body2"
              className="text-gray-600"
              style={{
                fontFamily: 'inherit',
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: '16px',
                lineHeight: '24px',
                letterSpacing: '0px',
                textAlign: 'center',
              }}
            >
              {t('forgotPassword.subtitle') ?? 'Ingresa tu correo electrónico y te enviaremos un link para restablecer tu contraseña.'}
            </Typography>
          </div>

          {/* Card blanca */}
          <div className="bg-white border border-gray-200 rounded-lg p-6 shadow-md">
            {/* Estado de éxito */}
            {resetLink && !loading && (
              <div className="text-center space-y-4">
                <div
                  className="rounded-lg p-4 border"
                  style={{
                    backgroundColor: '#d1fae5',
                    borderColor: '#10b981',
                  }}
                >
                  <Typography
                    variant="body2"
                    className="font-medium"
                    style={{ color: '#065f46' }}
                  >
                    {t('forgotPassword.success.title') ?? 'Link generado'}
                  </Typography>
                  <Typography
                    variant="body2"
                    className="mt-2"
                    style={{ color: '#047857', fontSize: '14px' }}
                  >
                    {t('forgotPassword.success.message') ?? 'Se ha generado un link de recuperación. Haz click en el enlace a continuación para restablecer tu contraseña.'}
                  </Typography>
                </div>
                {resetLink !== 'success' && (
                  <a
                    href={resetLink}
                    className="inline-block px-4 py-2 rounded-lg font-medium text-white hover:opacity-90 transition-opacity"
                    style={{ backgroundColor: '#2D5C63' }}
                  >
                    {t('forgotPassword.success.linkLabel') ?? 'Ir a restablecer contraseña'}
                  </a>
                )}
              </div>
            )}

            {/* Estado de carga */}
            {loading && (
              <div className="text-center space-y-4">
                <div
                  className="rounded-lg p-4 border"
                  style={{
                    backgroundColor: '#dbeafe',
                    borderColor: '#3b82f6',
                  }}
                >
                  <Typography
                    variant="body2"
                    className="font-medium"
                    style={{ color: '#1e40af' }}
                  >
                    {t('forgotPassword.sending') ?? 'Enviando...'}
                  </Typography>
                  <Typography
                    variant="body2"
                    className="mt-2"
                    style={{ color: '#1e3a8a', fontSize: '14px' }}
                  >
                    {t('forgotPassword.waitingMessage') ?? 'Espera, estamos procesando tu solicitud...'}
                  </Typography>
                  <Typography
                    variant="body2"
                    className="mt-2"
                    style={{ color: '#1e3a8a', fontSize: '13px' }}
                  >
                    {t('forgotPassword.waitingSubmessage') ?? 'Hemos enviado un link de recuperación a tu correo. Esto puede tardar unos momentos.'}
                  </Typography>
                </div>
              </div>
            )}

            {/* Estado de formulario */}
            {!resetLink && !loading && (
              <>
                {/* Botón volver */}
                {onBackToLogin && (
                  <button
                    type="button"
                    onClick={onBackToLogin}
                    className="flex items-center gap-2 mb-6 text-body-md hover:underline font-medium cursor-pointer"
                    style={{ color: '#2D5C63' }}
                  >
                    <Icon name="ArrowLeftIcon" variant="24-outline" size={18} />
                    <span>{t('forgotPassword.backToLogin') ?? 'Volver al inicio de sesión'}</span>
                  </button>
                )}

                {/* Formulario */}
                <form onSubmit={handleSubmit} className="space-y-4">
                  {/* Input de email */}
                  <div>
                    <label
                      className="block mb-2 font-medium text-sm"
                      style={{ color: '#2D5C63' }}
                    >
                      {t('login.email') ?? t('form.email') ?? 'Correo electrónico'}
                    </label>
                    <input
                      type="email"
                      placeholder={isEmailFocused ? '' : (t('login.emailPlaceholder') ?? t('placeholder.email') ?? 'Ingresa tu correo electrónico')}
                      value={email}
                      onChange={handleEmailChange}
                      onFocus={() => setIsEmailFocused(true)}
                      onBlur={() => setIsEmailFocused(false)}
                      className="w-full px-3 py-2 border rounded-lg focus:outline-none text-sm text-gray-900"
                      style={{
                        borderColor: errors.email ? '#ef4444' : (isEmailFocused ? '#38656D' : '#2D5C63'),
                        borderWidth: errors.email || isEmailFocused ? '2px' : '1px',
                        borderStyle: 'solid',
                      }}
                    />
                    {errors.email && (
                      <p className="mt-1 text-sm text-red-600">{errors.email}</p>
                    )}
                  </div>

                  {/* Error general */}
                  {error && (
                    <div
                      className="rounded-lg p-4 border anima-forgotpassword__errorBox"
                      style={{
                        backgroundColor: '#fecaca',
                        borderColor: '#ef4444',
                      }}
                    >
                      <Typography
                        variant="body2"
                        className="font-bold"
                        style={{ 
                          color: '#b91c1c',
                          fontFamily: FONT_FAMILY_MONO,
                          fontWeight: 400,
                          fontStyle: 'normal',
                          fontSize: '14px',
                          lineHeight: '21px',
                          letterSpacing: '0.02em',
                        }}
                      >
                        {error}
                      </Typography>
                    </div>
                  )}

                  {/* Botón de envío */}
                  <div className="pt-4">
                    <Button
                      tipo="Primary"
                      color="Teal"
                      tamaño="Default"
                      type="submit"
                      className="w-full"
                      disabled={loading || !hasAtSymbol(email)}
                    >
                      <span
                        style={{
                          fontFamily: FONT_FAMILY_SANS,
                          fontWeight: 400,
                          fontStyle: 'normal',
                          fontSize: '16px',
                          lineHeight: '24px',
                          letterSpacing: '0%',
                        }}
                      >
                        {loading
                          ? t('forgotPassword.sending') ?? 'Enviando...'
                          : t('forgotPassword.button') ?? 'Enviar link'}
                      </span>
                    </Button>
                  </div>
                </form>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ForgotPassword;

