import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '../../Atoms/Button/Button';
import { Typography } from '../../Atoms/Typography/Typography';
import { Input } from '../../Inputs/Input/Input';
import { PrimaryInput } from '../../Inputs/PrimaryInput/PrimaryInput';
import { Checkbox } from '../../Inputs/Checkbox/Checkbox';
import { PasswordInput } from '../../Inputs/PasswordInput/PasswordInput';
import { FONT_FAMILY_SANS, FONT_FAMILY_MONO } from '../../../designTokens';

/**
 * Formulario de login con soporte para variantes y login social.
 *
 * @param {Object} props
 * @param {string} [props.defaultEmail=''] - Valor inicial del campo email. Útil para prellenar desde datos guardados (ej. "recordar email" en localStorage).
 * @param {string} [props.defaultPassword=''] - Valor inicial del campo contraseña. Útil para prellenar desde datos guardados (ej. "recordar contraseña" en localStorage).
 * @param {boolean} [props.defaultRememberMe=false] - Valor inicial del checkbox "Recordarme". Útil para reflejar el estado guardado por el consumidor.
 */
export const LoginForm = ({
  variant,
  onSubmit,
  loading = false,
  onForgotPassword,
  onGoogleLogin,
  onMicrosoftLogin,
  showSocialLogin = true,
  showDivider = true,
  showPasswordRequirementsOnError = true,
  passwordRequirementsItems,
  passwordRequirementsTitle,
  passwordRequirementsPrefix,
  labels,
  generalError,
  generalErrorTitle,
  generalErrorSubtitle,
  defaultEmail = '',
  defaultPassword = '',
  defaultRememberMe = false,
  className = '',
  ...props
}) => {
  const { t } = useTranslation();
  const isHexaLogin = variant === 'hexa-login';
  const [formData, setFormData] = useState({
    email: defaultEmail ?? '',
    password: defaultPassword ?? '',
    rememberMe: defaultRememberMe ?? false,
  });
  const [errors, setErrors] = useState({});

  const handleChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: null }));
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const newErrors = {};

    if (!formData.email) {
      newErrors.email = t('form.email') + ' is required';
    }
    if (!formData.password) {
      newErrors.password = t('form.password') + ' is required';
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    if (onSubmit) {
      onSubmit(formData);
    }
  };

  const resolvedLabels = {
    emailLabel: labels?.emailLabel ?? t('form.email') ?? 'Email',
    passwordLabel: labels?.passwordLabel ?? t('form.password') ?? 'Contraseña',
    rememberMeLabel: labels?.rememberMeLabel ?? t('form.rememberMe') ?? 'Recordarme',
    forgotPasswordLabel: labels?.forgotPasswordLabel ?? t('form.forgotPassword') ?? 'Olvidé mi contraseña',
    continueWithLabel: labels?.continueWithLabel ?? 'Continuar con',
    googleLabel: labels?.googleLabel ?? 'Google',
    microsoftLabel: labels?.microsoftLabel ?? 'Microsoft',
  };

  const loginButtonText = loading ? (t('form.loggingIn') ?? 'Ingresando...') : (t('form.login') ?? 'Ingresar');

  return (
    isHexaLogin ? (
      <div className={`anima-loginform__container ${className}`} data-variant="hexa-login" {...props}>
        <div
          className="anima-loginform__card"
          style={{
            width: '100%',
            maxWidth: '427px',
            minHeight: '409px',
            opacity: 1,
            borderRadius: '14px',
            borderWidth: '1px',
            borderStyle: 'solid',
            borderColor: '#0000001A',
            padding: '24px',
            background: '#FFFFFF',
            boxSizing: 'border-box',
            boxShadow: '0px 4px 6px -4px #0000001A, 0px 10px 15px -3px #0000001A',
          }}
        >
        <form
          onSubmit={handleSubmit}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && ['INPUT', 'TEXTAREA'].includes(e.target?.tagName)) {
              const type = e.target.type;
              if (type !== 'checkbox' && type !== 'radio') {
                e.preventDefault();
                handleSubmit(e);
              }
            }
          }}
        >
          {/* 1) Email */}
          <PrimaryInput
            type="email"
            focusBorderOnFocus
            label={resolvedLabels.emailLabel}
            labelStyle={{ color: '#2D5C63' }}
            placeholder="Ingresa tu correo electronico"
            value={formData.email}
            onChange={(e) => handleChange('email', e.target.value)}
            error={errors.email}
            style={errors.email ? { borderColor: '#ef4444' } : undefined}
          />

        {/* 2) Password */}
        <div className="w-full mt-4">
          <PasswordInput
            variant="hexa-login"
            focusBorderOnFocus
            label={resolvedLabels.passwordLabel}
            labelClassName="block mb-2 font-medium text-sm"
            labelStyle={{ color: '#2D5C63' }}
            placeholder={t('placeholder.password')}
            value={formData.password}
            onChange={(e) => handleChange('password', e.target.value)}
            inputClassName="w-full px-3 py-2 border rounded-lg focus:outline-none text-sm text-gray-900 anima-passwordfield__input"
            style={{
              borderColor: errors.password ? '#ef4444' : '#2D5C63',
            }}
          />
        </div>

        {/* 3) Password requirements box (solo si hay error de password) */}
        {showPasswordRequirementsOnError && !!errors.password && (
          <div
            className="anima-loginform__requirementsBox rounded-lg p-4 border mt-4"
            style={{
              background: '#f5f3ff',
              borderColor: '#a78bfa',
              color: '#0c4a6e',
              fontFamily: FONT_FAMILY_MONO,
            }}
          >
            <Typography
              variant="body2"
              className="text-sm"
              style={{ 
                color: '#0c4a6e',
                fontFamily: FONT_FAMILY_MONO,
                whiteSpace: 'pre-line',
              }}
            >
              {passwordRequirementsTitle || (() => {
                const prefix = passwordRequirementsPrefix || t('form.passwordRequirementsPrefix') || 'Recuerda que la contraseña debe tener:';
                const defaultItems = passwordRequirementsItems || [
                  t('form.passwordRequirementMinChars') || 'Un mínimo de 6 caracteres',
                  t('form.passwordRequirementOther') || 'Una mayúscula, un número, un carácter especial',
                ];
                
                if (passwordRequirementsItems && passwordRequirementsItems.length > 0) {
                  return `${prefix}\n${passwordRequirementsItems[0]}\n\n${passwordRequirementsItems.slice(1).join(', ')}`;
                }
                return `${prefix}\n${defaultItems[0]}\n\n${defaultItems[1]}`;
              })()}
            </Typography>
          </div>
        )}

        {/* 4) Row remember/forgot */}
        <div className="flex items-center justify-between mt-4">
          <label className="flex items-center cursor-pointer" htmlFor="anima-loginform-remember">
            <input
              id="anima-loginform-remember"
              type="checkbox"
              checked={formData.rememberMe}
              onChange={(e) => handleChange('rememberMe', e.target.checked)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  e.target.click();
                }
              }}
              className="w-4 h-4 border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-[#2D5C63] focus:ring-offset-1"
              style={{
                accentColor: '#2D5C63',
                borderColor: formData.rememberMe ? '#2D5C63' : '#d1d5db',
              }}
              aria-label={resolvedLabels.rememberMeLabel}
            />
            <span className="ml-2 text-sm font-medium select-none" style={{ color: '#2D5C63' }}>
              {resolvedLabels.rememberMeLabel}
            </span>
          </label>

          <a
            href="#"
            className="text-body-md hover:underline font-medium"
            style={{ color: '#2D5C63', whiteSpace: 'nowrap' }}
            onClick={(e) => {
              e.preventDefault();
              if (onForgotPassword) onForgotPassword();
            }}
          >
            {resolvedLabels.forgotPasswordLabel}
          </a>
        </div>

        {/* 5) Error general box rojo (si existe) */}
        {(generalError || errors.general) && (
          <div
            className="anima-loginform__errorBox mt-4"
            style={{
              paddingTop: '12px',
              paddingRight: '16px',
              paddingBottom: '12px',
              paddingLeft: '16px',
              gap: '4px',
              borderRadius: '8px',
              borderWidth: '1px',
              border: '1px solid #B30808',
              backgroundColor: '#F8DBDB',
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            <Typography
              variant="body2"
              style={{
                fontFamily: FONT_FAMILY_MONO,
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: '14px',
                lineHeight: '21px',
                letterSpacing: '0.02em',
                color: '#B30808',
                margin: 0,
              }}
            >
              {generalErrorTitle ?? 
               (typeof generalError === 'string' ? generalError : null) ?? 
               (errors.general && typeof errors.general === 'string' ? errors.general : null) ??
               (t('errors.invalidCredentials') ?? 'Correo o contraseña incorrectos.')}
            </Typography>
            <Typography
              variant="body2"
              style={{
                fontFamily: FONT_FAMILY_MONO,
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: '14px',
                lineHeight: '21px',
                letterSpacing: '0.02em',
                color: '#B30808',
                margin: 0,
              }}
            >
              {generalErrorSubtitle ?? 
               (t('errors.tryAgain') ?? 'Intentá nuevamente.')}
            </Typography>
          </div>
        )}

        {/* 6) Botón login - type="button" evita submit implícito que duplicaba el foco en el tab order */}
        <div className="mt-4">
          <Button
            type="button"
            tipo="Primary"
            color="Teal"
            tamaño="Default"
            className="w-full"
            disabled={loading}
            onClick={(e) => {
              e.preventDefault();
              handleSubmit(e);
            }}
          >
            <span
              style={{
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: '16px',
                lineHeight: '24px',
                letterSpacing: '0%',
              }}
            >
              {loginButtonText}
            </span>
          </Button>
        </div>

        {/* 7) Divider */}
        {showDivider && (
          <div className="flex items-center gap-3 my-6">
            <div className="flex-1" style={{ borderTop: '1px solid #2D5C63' }} />
            <Typography
              variant="body2"
              className="text-body-md font-medium"
              style={{ color: '#2D5C63', whiteSpace: 'nowrap' }}
            >
              {resolvedLabels.continueWithLabel}
            </Typography>
            <div className="flex-1" style={{ borderTop: '1px solid #2D5C63' }} />
          </div>
        )}

        {/* 8) Social buttons */}
        {showSocialLogin && (
          <div
            className="anima-loginform__socialRow"
            style={{
              width: '100%',
              minHeight: '36px',
              display: 'flex',
              flexWrap: 'nowrap',
              gap: '12px',
              opacity: 1,
              boxSizing: 'border-box',
            }}
          >
            <button
              type="button"
              onClick={onGoogleLogin}
              className="anima-loginform__socialButton anima-loginform__socialButton--google"
              style={{
                flex: '1 1 0',
                minWidth: 0,
                height: '36px',
                paddingTop: '8px',
                paddingRight: '16px',
                paddingBottom: '8px',
                paddingLeft: '16px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '8px',
                borderRadius: '8px',
                borderWidth: '1px',
                borderStyle: 'solid',
                borderColor: '#38656D',
                background: '#FFFFFF',
                opacity: 1,
                boxSizing: 'border-box',
                cursor: 'pointer',
              }}
            >
              <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true" style={{ flexShrink: 0 }}>
                <path fill="#FFC107" d="M43.611 20.083H42V20H24v8h11.303C33.651 32.659 29.227 36 24 36c-6.627 0-12-5.373-12-12s5.373-12 12-12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.047 6.053 29.272 4 24 4 12.955 4 4 12.955 4 24s8.955 20 20 20 20-8.955 20-20c0-1.341-.138-2.65-.389-3.917z" />
                <path fill="#FF3D00" d="M6.306 14.691l6.571 4.819C14.655 16.108 19.002 12 24 12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.047 6.053 29.272 4 24 4 16.318 4 9.656 8.337 6.306 14.691z" />
                <path fill="#4CAF50" d="M24 44c5.166 0 9.86-1.977 13.409-5.197l-6.19-5.238C29.211 35.091 26.715 36 24 36c-5.205 0-9.616-3.318-11.281-7.946l-6.522 5.025C9.505 39.556 16.227 44 24 44z" />
                <path fill="#1976D2" d="M43.611 20.083H42V20H24v8h11.303c-.793 2.116-2.318 3.91-4.284 5.238l.003-.002 6.19 5.238C36.971 39.205 44 34 44 24c0-1.341-.138-2.65-.389-3.917z" />
              </svg>
              <Typography variant="body2" className="text-gray-900 font-medium" style={{ margin: 0, whiteSpace: 'nowrap' }}>
                {resolvedLabels.googleLabel}
              </Typography>
            </button>

            <button
              type="button"
              onClick={onMicrosoftLogin}
              className="anima-loginform__socialButton anima-loginform__socialButton--microsoft"
              style={{
                flex: '1 1 0',
                minWidth: 0,
                height: '36px',
                paddingTop: '8px',
                paddingRight: '16px',
                paddingBottom: '8px',
                paddingLeft: '16px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '8px',
                borderRadius: '8px',
                borderWidth: '1px',
                borderStyle: 'solid',
                borderColor: '#38656D',
                background: '#FFFFFF',
                opacity: 1,
                boxSizing: 'border-box',
                cursor: 'pointer',
              }}
            >
              <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true" style={{ flexShrink: 0 }}>
                <path fill="#F25022" d="M6 6h17v17H6z" />
                <path fill="#7FBA00" d="M25 6h17v17H25z" />
                <path fill="#00A4EF" d="M6 25h17v17H6z" />
                <path fill="#FFB900" d="M25 25h17v17H25z" />
              </svg>
              <Typography variant="body2" className="text-gray-900 font-medium" style={{ margin: 0, whiteSpace: 'nowrap' }}>
                {resolvedLabels.microsoftLabel}
              </Typography>
            </button>
          </div>
        )}
        </form>
        </div>
      </div>
    ) : (
      <form
        onSubmit={handleSubmit}
        className={`max-w-md mx-auto bg-white p-6 rounded-lg shadow-md ${className}`}
        {...props}
      >
        <h2 className="text-2xl font-bold mb-6 text-center">{t('form.login')}</h2>

        <div className="space-y-4">
          <Input
            label={t('form.email')}
            type="email"
            placeholder={t('placeholder.email')}
            value={formData.email}
            onChange={(e) => handleChange('email', e.target.value)}
            error={errors.email}
            required
          />

          <Input
            label={t('form.password')}
            type="password"
            placeholder={t('placeholder.password')}
            value={formData.password}
            onChange={(e) => handleChange('password', e.target.value)}
            error={errors.password}
            required
          />

          <Checkbox
            label={t('form.rememberMe')}
            checked={formData.rememberMe}
            onChange={(e) => handleChange('rememberMe', e.target.checked)}
          />

          <Button type="submit" variant="primary" className="w-full">
            {t('form.login')}
          </Button>

          <div className="text-center">
            <a href="#" className="text-sm text-blue-600 hover:underline">
              {t('form.forgotPassword')}
            </a>
          </div>
        </div>
      </form>
    )
  );
};

export default LoginForm;

