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

export const NewPassword = ({
  variant = 'default',
  layout = 'embedded',
  // Título y subtítulo
  title,
  subtitle,
  // Password field
  passwordLabel,
  passwordPlaceholder,
  passwordValue,
  onPasswordChange,
  passwordError,
  // Confirm field
  confirmPasswordLabel,
  confirmPasswordPlaceholder,
  confirmPasswordValue,
  onConfirmPasswordChange,
  confirmPasswordError,
  // Requirements box
  requirementsTitle,
  requirementsItems = [],
  requirementsPrefix,
  showRequirements = true,
  // General error
  generalError,

  // Error de consistencia: las contraseñas no coinciden (controlado por el consumidor)
  showPasswordMismatch = false,
  passwordMismatchMessage = 'No coinciden las contraseñas.',
  passwordMismatchClassName = '',
  passwordMismatchStyle,
  // Actions
  cancelLabel,
  submitLabel,
  onCancel,
  onSubmit,
  disabled = false,
  submitting = false,
  // Success
  success = false,
  successTitle,
  successMessage,
  successExtra,
  className = '',
  ...props
}) => {
  const { t } = useTranslation();
  const isHexaLogin = variant === 'hexa-login';
  const isPageLayout = layout === 'page';
  const mismatchBorderStyle = showPasswordMismatch ? { border: '2px solid #B30808' } : undefined;

  const handleSubmit = (e) => {
    e.preventDefault();
    if (onSubmit && !disabled && !submitting) {
      onSubmit({
        password: passwordValue,
        confirmPassword: confirmPasswordValue,
      });
    }
  };

  // Si está en modo success, mostrar solo el mensaje de éxito
  if (success) {
    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 */}
            {(title || subtitle) && (
              <div className="mb-8 text-center">
                {title && (
                  <Typography
                    variant="h3"
                    className="mb-2 font-semibold"
                    style={
                      isHexaLogin
                        ? {
                            color: '#2D5C63',
                            fontFamily: 'inherit',
                            fontWeight: 400,
                            fontStyle: 'normal',
                            fontSize: '32px',
                            lineHeight: '48px',
                            letterSpacing: '0px',
                            textAlign: 'center',
                          }
                        : undefined
                    }
                  >
                    {title}
                  </Typography>
                )}
                {subtitle && (
                  <Typography
                    variant="body2"
                    className="text-gray-600"
                    style={
                      isHexaLogin
                        ? {
                            fontFamily: 'inherit',
                            fontWeight: 400,
                            fontStyle: 'normal',
                            fontSize: '16px',
                            lineHeight: '24px',
                            letterSpacing: '0px',
                            textAlign: 'center',
                          }
                        : undefined
                    }
                  >
                    {subtitle}
                  </Typography>
                )}
              </div>
            )}

            {/* Card blanca */}
            <div className="bg-white border border-gray-200 rounded-lg p-6 shadow-md">
              {/* Success box */}
              <div
                className="rounded-lg p-4 border"
                style={{
                  backgroundColor: '#d1fae5',
                  borderColor: '#10b981',
                }}
              >
                {successTitle && (
                  <Typography
                    variant="body2"
                    className="font-medium"
                    style={{ color: '#065f46' }}
                  >
                    {successTitle}
                  </Typography>
                )}
                {successMessage && (
                  <Typography
                    variant="body2"
                    className={successTitle ? 'mt-2' : ''}
                    style={{ color: '#047857', fontSize: '14px' }}
                  >
                    {successMessage}
                  </Typography>
                )}
                {successExtra && <div className="mt-4">{successExtra}</div>}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  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 */}
          {(title || subtitle) && (
            <div className="mb-8 text-center">
              {title && (
                <Typography
                  variant="h3"
                  className="mb-2 font-semibold"
                  style={
                    isHexaLogin
                      ? {
                          color: '#2D5C63',
                          fontFamily: 'inherit',
                          fontWeight: 400,
                          fontStyle: 'normal',
                          fontSize: '32px',
                          lineHeight: '48px',
                          letterSpacing: '0px',
                          textAlign: 'center',
                        }
                      : undefined
                  }
                >
                  {title}
                </Typography>
              )}
              {subtitle && (
                <Typography
                  variant="body2"
                  className="text-gray-600"
                  style={
                    isHexaLogin
                      ? {
                          fontFamily: 'inherit',
                          fontWeight: 400,
                          fontStyle: 'normal',
                          fontSize: '16px',
                          lineHeight: '24px',
                          letterSpacing: '0px',
                          textAlign: 'center',
                        }
                      : undefined
                  }
                >
                  {subtitle}
                </Typography>
              )}
            </div>
          )}

          {/* Card blanca */}
          <div className="bg-white border border-gray-200 rounded-lg p-6 shadow-md">
            <form onSubmit={handleSubmit} className="space-y-4">
              {/* Password field */}
              <div>
                <PasswordInput
                  variant={isHexaLogin ? 'hexa-login' : undefined}
                  clearPlaceholderOnFocus
                  focusBorderOnFocus
                  label={passwordLabel}
                  labelClassName={isHexaLogin ? 'block mb-2 font-medium text-sm' : undefined}
                  labelStyle={isHexaLogin ? { color: '#2D5C63' } : undefined}
                  placeholder={passwordPlaceholder}
                  value={passwordValue || ''}
                  onChange={onPasswordChange}
                  error={passwordError}
                  inputClassName={
                    isHexaLogin
                      ? 'w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm text-gray-900 anima-passwordfield__input'
                      : undefined
                  }
                  style={
                    isHexaLogin
                      ? {
                          borderColor: passwordError ? '#ef4444' : '#2D5C63',
                          borderWidth: '1px',
                          borderStyle: 'solid',
                          ...(mismatchBorderStyle || {}),
                        }
                      : (mismatchBorderStyle || undefined)
                  }
                />
              </div>

              {/* Confirm password field */}
              <div>
                <PasswordInput
                  variant={isHexaLogin ? 'hexa-login' : undefined}
                  clearPlaceholderOnFocus
                  focusBorderOnFocus
                  label={confirmPasswordLabel}
                  labelClassName={isHexaLogin ? 'block mb-2 font-medium text-sm' : undefined}
                  labelStyle={isHexaLogin ? { color: '#2D5C63' } : undefined}
                  placeholder={confirmPasswordPlaceholder}
                  value={confirmPasswordValue || ''}
                  onChange={onConfirmPasswordChange}
                  error={confirmPasswordError}
                  inputClassName={
                    isHexaLogin
                      ? 'w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm text-gray-900 anima-passwordfield__input'
                      : undefined
                  }
                  style={
                    isHexaLogin
                      ? {
                          borderColor: confirmPasswordError ? '#ef4444' : '#2D5C63',
                          borderWidth: '1px',
                          borderStyle: 'solid',
                          ...(mismatchBorderStyle || {}),
                        }
                      : (mismatchBorderStyle || undefined)
                  }
                />
                {showPasswordMismatch && passwordMismatchMessage ? (
                  <Typography
                    variant="body2"
                    className={passwordMismatchClassName}
                    style={{
                      fontFamily: 'IBM Plex Mono',
                      fontWeight: 700,
                      fontStyle: 'normal',
                      fontSize: '12px',
                      lineHeight: '18px',
                      letterSpacing: '2%',
                      color: '#B30808',
                      marginTop: '6px',
                      ...(passwordMismatchStyle || {}),
                    }}
                  >
                    {passwordMismatchMessage}
                  </Typography>
                ) : null}
              </div>

              {/* Requirements box */}
              {showRequirements && requirementsItems.length > 0 && (
                <div
                  className="rounded-lg p-4 border"
                  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',
                    }}
                  >
                    {requirementsTitle || (() => {
                      const prefix = requirementsPrefix || t('form.passwordRequirementsPrefix') || 'Recuerda que la contraseña debe tener:';
                      const defaultItems = requirementsItems.length > 0 ? requirementsItems : [
                        t('form.passwordRequirementMinChars') || 'Un mínimo de 6 caracteres',
                        t('form.passwordRequirementOther') || 'Una mayúscula, un número, un carácter especial',
                      ];
                      
                      if (defaultItems.length > 0) {
                        return `${prefix}\n\n${defaultItems.map(item => `• ${item}`).join('\n')}`;
                      }
                      return prefix;
                    })()}
                  </Typography>
                </div>
              )}

              {/* General error */}
              {generalError && (
                <div
                  className="rounded-lg p-4 border"
                  style={{
                    backgroundColor: '#fecaca',
                    borderColor: '#ef4444',
                  }}
                >
                  <Typography
                    variant="body2"
                    className="font-bold"
                    style={{ color: '#b91c1c' }}
                  >
                    {generalError}
                  </Typography>
                </div>
              )}

              {/* Botonera 2 columnas */}
              <div className="flex gap-4 pt-4">
                {onCancel && (
                  <Button
                    type="button"
                    tipo="Secondary"
                    color="Teal"
                    tamaño="Default"
                    className="flex-1"
                    onClick={onCancel}
                    disabled={disabled || submitting}
                  >
                    <span
                      style={
                        isHexaLogin
                          ? {
                              fontFamily: FONT_FAMILY_SANS,
                              fontWeight: 400,
                              fontStyle: 'normal',
                              fontSize: '16px',
                              lineHeight: '24px',
                              letterSpacing: '0%',
                            }
                          : undefined
                      }
                    >
                      {cancelLabel || 'Cancelar'}
                    </span>
                  </Button>
                )}
                <Button
                  type="submit"
                  tipo="Primary"
                  color="Teal"
                  tamaño="Default"
                  className={onCancel ? 'flex-1' : 'w-full'}
                  disabled={disabled || submitting}
                >
                  <span
                    style={
                      isHexaLogin
                        ? {
                            fontFamily: FONT_FAMILY_SANS,
                            fontWeight: 400,
                            fontStyle: 'normal',
                            fontSize: '16px',
                            lineHeight: '24px',
                            letterSpacing: '0%',
                          }
                        : undefined
                    }
                  >
                    {submitting ? 'Guardando...' : submitLabel || 'Guardar'}
                  </span>
                </Button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default NewPassword;

