import { useState, useEffect, useLayoutEffect } from 'react';
import { Typography } from '../../Atoms/Typography/Typography';
import { PasswordInput } from '../../Inputs/PasswordInput/PasswordInput';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { Skeleton } from '../../Atoms/Skeleton/Skeleton';
import { CardGrande } from '../CardGrande/CardGrande';
import { Icon } from '../../Atoms/Icon/Icon';
import { FONT_FAMILY_MONO } from '../../../designTokens';

export const CambiarContrasena = ({
  // Estado de carga (skeleton)
  loading = false,

  // Título principal
  title = 'Cambiar contraseña',
  titleStyle,
  titleClassName = '',
  showCloseButton = true,
  onClose,
  closeButtonAriaLabel = 'Cerrar',
  closeButtonClassName = '',
  closeButtonStyle,

  // Campo 1
  firstInputLabel = 'Contraseña actual',
  firstInputLabelStyle,
  firstInputLabelClassName = '',
  firstInputType = 'password',
  firstInputValue = '',
  firstInputOnChange,
  firstInputPlaceholder = '',
  firstInputDisabled = false,
  firstInputError = '',
  firstInputClassName = '',
  firstInputStyle,
  showCurrentPasswordInvalid = false,
  currentPasswordInvalidMessage = 'La contraseña actual no es correcta.',
  currentPasswordInvalidClassName = '',
  currentPasswordInvalidStyle,

  // Campo 2
  secondInputLabel = 'Nueva contraseña',
  secondInputLabelStyle,
  secondInputLabelClassName = '',
  secondInputType = 'password',
  secondInputValue = '',
  secondInputOnChange,
  secondInputPlaceholder = '',
  secondInputDisabled = false,
  secondInputError = '',
  secondInputClassName = '',
  secondInputStyle,
  /**
   * Mensaje de requisitos para la nueva contraseña.
   * Se envía por props desde el consumidor para soportar i18n (es/en) sin hardcode.
   */
  passwordRequirementsMessage = 'Recuerda que la contraseña debe tener:\n\n• Un mínimo de 6 caracteres\n• Una mayúscula, un número, un carácter especial',
  showPasswordRequirements = true,
  passwordRequirementsClassName = '',
  passwordRequirementsStyle,

  // Error de consistencia: las contraseñas no coinciden (se controla desde el consumidor).
  // Idealmente se activa desde los onChange del consumidor cuando secondInputValue !== thirdInputValue.
  showPasswordMismatch = false,
  passwordMismatchMessage = 'No coinciden las contraseñas.',
  passwordMismatchClassName = '',
  passwordMismatchStyle,

  // Campo 3
  thirdInputLabel = 'Repetir tu contraseña',
  thirdInputLabelStyle,
  thirdInputLabelClassName = '',
  thirdInputType = 'password',
  thirdInputValue = '',
  thirdInputOnChange,
  thirdInputPlaceholder = '',
  thirdInputDisabled = false,
  thirdInputError = '',
  thirdInputClassName = '',
  thirdInputStyle,

  // Footer: botón guardar
  guardarButtonText = 'Guardar',
  guardarButtonDisabled = true,
  guardarButtonOnClick,
  guardarButtonStyle,
  guardarButtonClassName = '',

  // Contenedores
  containerStyle,
  containerClassName = '',
  titleContainerStyle,
  titleContainerClassName = '',
  contentContainerStyle,
  contentContainerClassName = '',

  // Breakpoint (resolución): narrow hasta este ancho; por defecto 1023
  breakpointNarrowPx = 1023,

  className = '',
  ...props
}) => {
  const [isNarrow, setIsNarrow] = useState(() =>
    typeof window !== 'undefined' ? window.innerWidth <= breakpointNarrowPx : false
  );
  const [isVisible, setIsVisible] = useState(true);

  const updateBreakpoint = () => {
    setIsNarrow(window.innerWidth <= breakpointNarrowPx);
  };

  useLayoutEffect(() => {
    updateBreakpoint();
  }, [breakpointNarrowPx]);

  useEffect(() => {
    window.addEventListener('resize', updateBreakpoint);
    return () => window.removeEventListener('resize', updateBreakpoint);
  }, [breakpointNarrowPx]);

  const handleClose = () => {
    if (typeof onClose === 'function') {
      onClose();
      return;
    }
    setIsVisible(false);
  };

  if (!isVisible) return null;

  const inlineMismatchTextStyle = {
    fontFamily: 'IBM Plex Mono',
    fontWeight: 700,
    fontStyle: 'normal',
    fontSize: '12px',
    lineHeight: '18px',
    letterSpacing: '2%',
    color: '#B30808',
    margin: '6px 0 0',
  };

  const currentPasswordBorderStyle = showCurrentPasswordInvalid ? { border: '2px solid #B30808' } : undefined;
  const mismatchBorderStyle = showPasswordMismatch ? { border: '2px solid #B30808' } : undefined;

  return (
    <CardGrande
      className={`anima-cambiarcontrasena__container ${containerClassName} ${className}`}
      style={{
        ...(containerStyle || {}),
      }}
      {...props}
    >
      {/* Div padre título */}
      <div
        className={`anima-cambiarcontrasena__title-container ${titleContainerClassName}`}
        style={{
          width: '100%',
          ...(isNarrow ? { minHeight: 0 } : { minHeight: '58px' }),
          paddingTop: '24px',
          paddingRight: isNarrow ? '16px' : '24px',
          paddingBottom: '4px',
          paddingLeft: isNarrow ? '16px' : '24px',
          gap: '8px',
          opacity: 1,
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          ...(titleContainerStyle || {}),
        }}
      >
        <div
          style={{
            width: '100%',
            minHeight: '30px',
            opacity: 1,
            boxSizing: 'border-box',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: '12px',
          }}
        >
          {loading ? (
            <Skeleton variant="rectangular" height={24} width="70%" />
          ) : title ? (
            <Typography
              variant="body-md"
              className={titleClassName}
              style={{
                fontFamily: 'IBM Plex Sans, sans-serif',
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: '20px',
                lineHeight: '30px',
                letterSpacing: '0%',
                verticalAlign: 'middle',
                color: 'var(--color-cyan-19)',
                margin: 0,
                ...(titleStyle || {}),
              }}
            >
              {title}
            </Typography>
          ) : null}

          {showCloseButton ? (
            <button
              type="button"
              aria-label={closeButtonAriaLabel}
              className={closeButtonClassName}
              onClick={handleClose}
              style={{
                border: 'none',
                background: 'transparent',
                padding: 0,
                margin: 0,
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                flexShrink: 0,
                ...(closeButtonStyle || {}),
              }}
            >
              <Icon
                name="XMarkIcon"
                variant="24-outline"
                size={20}
                style={{ width: 20, height: 20, color: 'var(--color-cyan-19)' }}
              />
            </button>
          ) : null}
        </div>
      </div>

      {/* Div contenido */}
      <div
        className={`anima-cambiarcontrasena__content ${contentContainerClassName}`}
        style={{
          width: '100%',
          flex: 1,
          opacity: 1,
          boxSizing: 'border-box',
          paddingTop: '16px',
          paddingRight: isNarrow ? '16px' : '24px',
          paddingBottom: '24px',
          paddingLeft: isNarrow ? '16px' : '24px',
          display: 'flex',
          flexDirection: 'column',
          gap: '24px',
          ...(contentContainerStyle || {}),
        }}
      >
        {loading ? (
          <>
            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Skeleton variant="rectangular" height={21} width={180} />
              <Skeleton variant="rectangular" height={42} width="100%" />
            </div>
            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Skeleton variant="rectangular" height={21} width={140} />
              <Skeleton variant="rectangular" height={42} width="100%" />
            </div>
            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Skeleton variant="rectangular" height={21} width={170} />
              <Skeleton variant="rectangular" height={42} width="100%" />
            </div>
            <div
              style={{
                width: '100%',
                display: 'flex',
                flexDirection: 'column',
                gap: '16px',
                boxSizing: 'border-box',
                marginTop: 'auto',
              }}
            >
              <Skeleton
                variant="rectangular"
                height={48}
                width={isNarrow ? '100%' : 91}
                style={{ borderRadius: 8 }}
              />
            </div>
          </>
        ) : (
          <>
            <div
              style={{
                width: '100%',
                ...(isNarrow ? { minHeight: 0, paddingBottom: 0 } : {}),
                gap: '24px',
                opacity: 1,
                boxSizing: 'border-box',
                display: 'flex',
                flexDirection: 'column',
              }}
            >
              <div
                style={{
                  width: '100%',
                  ...(isNarrow ? { minHeight: 0 } : { minHeight: '71px' }),
                  gap: '10px',
                  opacity: 1,
                  boxSizing: 'border-box',
                  display: 'flex',
                  flexDirection: 'column',
                }}
              >
                <PasswordInput
                  clearPlaceholderOnFocus
                  focusBorderOnFocus
                  variant="hexa-login"
                  label={firstInputLabel}
                  labelStyle={firstInputLabelStyle}
                  labelClassName={firstInputLabelClassName}
                  type={firstInputType}
                  value={firstInputValue}
                  onChange={firstInputOnChange}
                  placeholder={firstInputPlaceholder}
                  disabled={firstInputDisabled}
                  error={firstInputError}
                  className={firstInputClassName}
                  inputClassName="w-full px-3 py-2 border rounded-lg focus:outline-none text-sm text-gray-900 anima-passwordfield__input"
                  style={{
                    ...(firstInputStyle || {}),
                    ...(currentPasswordBorderStyle || {}),
                  }}
                />
                {showCurrentPasswordInvalid && currentPasswordInvalidMessage ? (
                  <Typography
                    variant="body2"
                    className={currentPasswordInvalidClassName}
                    style={{
                      ...inlineMismatchTextStyle,
                      ...(currentPasswordInvalidStyle || {}),
                    }}
                  >
                    {currentPasswordInvalidMessage}
                  </Typography>
                ) : null}
              </div>

              {/* Separador entre "Contraseña actual" y "Nueva contraseña" */}
              <div
                style={{
                  width: '100%',
                  height: '1px',
                  backgroundColor: '#D9D9D9',
                }}
              />

              <div
                style={{
                  width: '100%',
                  ...(isNarrow ? { minHeight: 0 } : { minHeight: '71px' }),
                  gap: '10px',
                  opacity: 1,
                  boxSizing: 'border-box',
                  display: 'flex',
                  flexDirection: 'column',
                }}
              >
                <PasswordInput
                  clearPlaceholderOnFocus
                  focusBorderOnFocus
                  variant="hexa-login"
                  label={secondInputLabel}
                  labelStyle={secondInputLabelStyle}
                  labelClassName={secondInputLabelClassName}
                  type={secondInputType}
                  value={secondInputValue}
                  onChange={secondInputOnChange}
                  placeholder={secondInputPlaceholder}
                  disabled={secondInputDisabled}
                  error={secondInputError}
                  className={secondInputClassName}
                  inputClassName="w-full px-3 py-2 border rounded-lg focus:outline-none text-sm text-gray-900 anima-passwordfield__input"
                  style={{
                    ...(secondInputStyle || {}),
                    ...(mismatchBorderStyle || {}),
                  }}
                />
              </div>

              <div
                style={{
                  width: '100%',
                  ...(isNarrow ? { minHeight: 0 } : { minHeight: '71px' }),
                  gap: '10px',
                  opacity: 1,
                  boxSizing: 'border-box',
                  display: 'flex',
                  flexDirection: 'column',
                }}
              >
                <PasswordInput
                  clearPlaceholderOnFocus
                  focusBorderOnFocus
                  variant="hexa-login"
                  label={thirdInputLabel}
                  labelStyle={thirdInputLabelStyle}
                  labelClassName={thirdInputLabelClassName}
                  type={thirdInputType}
                  value={thirdInputValue}
                  onChange={thirdInputOnChange}
                  placeholder={thirdInputPlaceholder}
                  disabled={thirdInputDisabled}
                  error={thirdInputError}
                  className={thirdInputClassName}
                  inputClassName="w-full px-3 py-2 border rounded-lg focus:outline-none text-sm text-gray-900 anima-passwordfield__input"
                  style={{
                    ...(thirdInputStyle || {}),
                    ...(mismatchBorderStyle || {}),
                  }}
                />
                {showPasswordMismatch && passwordMismatchMessage ? (
                  <Typography
                    variant="body2"
                    className={passwordMismatchClassName}
                    style={{
                      ...inlineMismatchTextStyle,
                      ...(passwordMismatchStyle || {}),
                    }}
                  >
                    {passwordMismatchMessage}
                  </Typography>
                ) : null}
              </div>

              {showPasswordRequirements && passwordRequirementsMessage ? (
                <div
                  className={`anima-cambiarcontrasena__requirements ${passwordRequirementsClassName}`.trim()}
                  style={{
                    width: '100%',
                    borderRadius: '8px',
                    border: '1px solid #A78BFA',
                    background: '#F5F3FF',
                    padding: '12px 16px',
                    boxSizing: 'border-box',
                    ...(passwordRequirementsStyle || {}),
                  }}
                >
                  <Typography
                    variant="body-sm"
                    style={{
                      fontFamily: FONT_FAMILY_MONO,
                      fontSize: '0.875rem',
                      color: '#0C4A6E',
                      whiteSpace: 'pre-line',
                      margin: 0,
                    }}
                  >
                    {passwordRequirementsMessage}
                  </Typography>
                </div>
              ) : null}
            </div>

            {isNarrow ? (
              <div
                style={{
                  width: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  gap: '16px',
                  boxSizing: 'border-box',
                  marginTop: 'auto',
                }}
              >
                <PrimaryActionButton
                  text={guardarButtonText}
                  disabled={guardarButtonDisabled}
                  onClick={guardarButtonOnClick}
                  fullWidth
                  className={guardarButtonClassName}
                  style={guardarButtonStyle}
                />
              </div>
            ) : (
              <div
                style={{
                  width: '100%',
                  marginTop: 'auto',
                  gap: '20px',
                  opacity: 1,
                  boxSizing: 'border-box',
                  display: 'flex',
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'flex-end',
                  flexWrap: 'nowrap',
                }}
              >
                <PrimaryActionButton
                  text={guardarButtonText}
                  disabled={guardarButtonDisabled}
                  onClick={guardarButtonOnClick}
                  fullWidth={false}
                  className={guardarButtonClassName}
                  style={guardarButtonStyle}
                />
              </div>
            )}
          </>
        )}
      </div>
    </CardGrande>
  );
};

export default CambiarContrasena;

