import { useState, useEffect, useLayoutEffect, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { setPortalLanguage } from '../../../i18n/config';
import { Typography } from '../../Atoms/Typography/Typography';
import { PrimarySelect } from '../../Inputs/PrimarySelect/PrimarySelect';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { Skeleton } from '../../Atoms/Skeleton/Skeleton';
import { FONT_FAMILY_SANS } from '../../../designTokens';
import { CardGrande } from '../CardGrande/CardGrande';
import { UltimaActualizacion } from '../UltimaActualizacion/UltimaActualizacion';

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

  // Título principal
  title,
  titleStyle,
  titleClassName = '',

  // Label del desplegable (idioma predeterminado)
  labelText,
  labelTextStyle,
  labelTextClassName = '',

  /**
   * Si es true y `selectOptions` está vacío, se muestran Español / English (es-AR | en-US)
   * y el cambio aplica `i18n.changeLanguage` + persistencia (localStorage).
   */
  builtinLanguageSelect = true,
  /** Si es true, al elegir es-AR o en-US se sincroniza i18next (también con opciones propias). */
  syncLanguageWithI18n = true,
  /** Tras cambiar idioma (códigos es-AR | en-US), p. ej. para guardar en API del portal. */
  onLanguageChange,

  // Desplegable: opciones cargadas por el consumidor (ej. desde API)
  selectOptions = [],
  selectValue = '',
  selectOnChange,
  selectPlaceholder,
  selectDisabled = false,
  selectClassName = '',
  selectStyle,

  // Zona horaria: segundo desplegable (también cargado por el consumidor)
  labelZonaHoraria,
  labelZonaHorariaStyle,
  labelZonaHorariaClassName = '',
  zonaHorariaOptions = [],
  zonaHorariaValue = '',
  zonaHorariaOnChange,
  zonaHorariaPlaceholder,
  zonaHorariaDisabled = false,
  zonaHorariaClassName = '',
  zonaHorariaStyle,

  // Última actualización (datos desde el consumidor, ej. API)
  showUltimaActualizacion = true,
  actualizacionLabel,
  actualizacionLabelStyle,
  actualizacionLabelClassName = '',
  actualizacionText,
  actualizacionTextStyle,
  actualizacionTextClassName = '',

  // Footer: botón guardar
  guardarButtonText,
  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 { t, i18n } = useTranslation();
  const [isNarrow, setIsNarrow] = useState(() =>
    typeof window !== 'undefined' ? window.innerWidth <= breakpointNarrowPx : false
  );
  const resolvedTitle = title ?? t('point.preferencias.title');
  const resolvedLabelText = labelText ?? t('preferences.languageLabel');
  const resolvedLabelZonaHoraria = labelZonaHoraria ?? t('preferences.timezoneLabel');
  const resolvedGuardarButtonText = guardarButtonText ?? t('common.save');
  const resolvedSelectPlaceholder = selectPlaceholder ?? t('preferences.placeholder.selectLanguage');
  const resolvedZonaHorariaPlaceholder = zonaHorariaPlaceholder ?? t('preferences.placeholder.selectTimezone');
  const resolvedActualizacionLabel = actualizacionLabel ?? t('preferences.lastUpdateLabel');
  const resolvedActualizacionText = actualizacionText ?? t('preferences.lastUpdateText');

  const builtinLanguageOptions = useMemo(
    () => [
      { value: 'es-AR', label: t('preferences.locale.esAR') },
      { value: 'en-US', label: t('preferences.locale.enUS') },
    ],
    [t]
  );

  const useBuiltinLanguage =
    builtinLanguageSelect && (!selectOptions || selectOptions.length === 0);

  const resolvedLanguageOptions = useBuiltinLanguage ? builtinLanguageOptions : selectOptions;

  const resolvedLanguageValue = useMemo(() => {
    if (!useBuiltinLanguage) {
      return selectValue ?? '';
    }
    if (selectValue !== undefined && selectValue !== '') {
      return selectValue;
    }
    const lng = i18n.language;
    if (lng === 'es-AR' || lng === 'en-US') return lng;
    return 'es-AR';
  }, [useBuiltinLanguage, selectValue, i18n.language]);

  const handleLanguageSelectChange = useCallback(
    (e) => {
      const v = e.target.value;
      if (syncLanguageWithI18n && (v === 'es-AR' || v === 'en-US')) {
        void setPortalLanguage(v);
        onLanguageChange?.(v);
      }
      if (selectOnChange) selectOnChange(e);
    },
    [syncLanguageWithI18n, onLanguageChange, selectOnChange]
  );

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

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

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

  return (
    <CardGrande
      className={`anima-preferencias__container ${containerClassName} ${className}`}
      style={{
        ...(containerStyle || {}),
      }}
      {...props}
    >
      {/* Div padre título */}
      <div
        className={`anima-preferencias__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 título */}
        <div
          style={{
            width: '100%',
            minHeight: '30px',
            opacity: 1,
            boxSizing: 'border-box',
          }}
        >
          {loading ? (
            <Skeleton variant="rectangular" height={24} width="70%" />
          ) : resolvedTitle ? (
            <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 || {}),
              }}
            >
              {resolvedTitle}
            </Typography>
          ) : null}
        </div>
      </div>

      {/* Div contenido */}
      <div
        className={`anima-preferencias__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 ? (
          <>
            {/* Skeleton: Idioma (predeterminado) */}
            <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>

            {/* Skeleton: Zona horaria */}
            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Skeleton variant="rectangular" height={21} width={120} />
              <Skeleton variant="rectangular" height={42} width="100%" />
            </div>

            {/* Skeleton: Última actualización + Guardar */}
            {showUltimaActualizacion ? (
              isNarrow ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginTop: 'auto' }}>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    <Skeleton variant="rectangular" height={21} width={180} />
                    <Skeleton variant="rectangular" height={21} width={100} style={{ marginLeft: 24 }} />
                  </div>
                  <Skeleton variant="rectangular" height={48} width="100%" style={{ borderRadius: 8 }} />
                </div>
              ) : (
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    gap: 20,
                    marginTop: 'auto',
                  }}
                >
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    <Skeleton variant="rectangular" height={21} width={180} />
                    <Skeleton variant="rectangular" height={21} width={100} style={{ marginLeft: 24 }} />
                  </div>
                  <Skeleton variant="rectangular" height={48} width={91} style={{ borderRadius: 8 }} />
                </div>
              )
            ) : (
              <div style={{ marginTop: 'auto' }}>
                <Skeleton variant="rectangular" height={48} width={isNarrow ? '100%' : 91} style={{ borderRadius: 8 }} />
              </div>
            )}
          </>
        ) : (
          <>
            {/* Bloque superior: Idioma + Zona horaria */}
            <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',
                }}
              >
                <PrimarySelect
                  label={resolvedLabelText}
                  labelStyle={labelTextStyle}
                  labelClassName={labelTextClassName}
                  options={resolvedLanguageOptions}
                  value={resolvedLanguageValue}
                  onChange={handleLanguageSelectChange}
                  placeholder={resolvedSelectPlaceholder}
                  disabled={selectDisabled}
                  className={selectClassName}
                  style={selectStyle}
                />
              </div>

              <div
                style={{
                  width: '100%',
                  ...(isNarrow ? { minHeight: 0 } : { minHeight: '71px' }),
                  gap: '10px',
                  opacity: 1,
                  boxSizing: 'border-box',
                  display: 'flex',
                  flexDirection: 'column',
                }}
              >
                <PrimarySelect
                  label={resolvedLabelZonaHoraria}
                  labelStyle={labelZonaHorariaStyle}
                  labelClassName={labelZonaHorariaClassName}
                  options={zonaHorariaOptions}
                  value={zonaHorariaValue}
                  onChange={zonaHorariaOnChange}
                  placeholder={resolvedZonaHorariaPlaceholder}
                  disabled={zonaHorariaDisabled}
                  className={zonaHorariaClassName}
                  style={zonaHorariaStyle}
                />
              </div>
            </div>

            {/* Última actualización + Guardar */}
            {showUltimaActualizacion ? (
              isNarrow ? (
                <div
                  style={{
                    width: '100%',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '16px',
                    boxSizing: 'border-box',
                    marginTop: 'auto',
                  }}
                >
                  <UltimaActualizacion
                    variant="narrow"
                    render="singleLine"
                    label={resolvedActualizacionLabel}
                    text={resolvedActualizacionText}
                    labelClassName={actualizacionLabelClassName}
                    labelStyle={actualizacionLabelStyle}
                    textClassName={actualizacionTextClassName}
                    textStyle={actualizacionTextStyle}
                  />
                  <PrimaryActionButton
                    text={resolvedGuardarButtonText}
                    disabled={guardarButtonDisabled}
                    onClick={guardarButtonOnClick}
                    fullWidth
                    className={guardarButtonClassName}
                    style={guardarButtonStyle}
                  />
                </div>
              ) : (
                <div
                  style={{
                    width: '100%',
                    minHeight: '69px',
                    marginTop: 'auto',
                    gap: '20px',
                    opacity: 1,
                    boxSizing: 'border-box',
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    flexWrap: 'nowrap',
                  }}
                >
                  <div
                    style={{
                      flex: '1 1 auto',
                      minWidth: 0,
                      paddingTop: '8px',
                      paddingRight: '12px',
                      paddingBottom: '8px',
                      paddingLeft: '12px',
                      gap: '4px',
                      opacity: 1,
                      boxSizing: 'border-box',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'flex-start',
                      justifyContent: 'center',
                    }}
                  >
                    <UltimaActualizacion
                      variant="wide"
                      render="singleLine"
                      label={resolvedActualizacionLabel}
                      text={resolvedActualizacionText}
                      labelClassName={actualizacionLabelClassName}
                      labelStyle={actualizacionLabelStyle}
                      textClassName={actualizacionTextClassName}
                      textStyle={actualizacionTextStyle}
                    />
                  </div>
                  <PrimaryActionButton
                    text={resolvedGuardarButtonText}
                    disabled={guardarButtonDisabled}
                    onClick={guardarButtonOnClick}
                    fullWidth={false}
                    className={guardarButtonClassName}
                    style={guardarButtonStyle}
                  />
                </div>
              )
            ) : (
              <div
                style={{
                  width: '100%',
                  marginTop: 'auto',
                  display: 'flex',
                  justifyContent: isNarrow ? 'stretch' : 'flex-end',
                }}
              >
                <PrimaryActionButton
                  text={resolvedGuardarButtonText}
                  disabled={guardarButtonDisabled}
                  onClick={guardarButtonOnClick}
                  fullWidth={isNarrow}
                  className={guardarButtonClassName}
                  style={guardarButtonStyle}
                />
              </div>
            )}
          </>
        )}
      </div>
    </CardGrande>
  );
};

export default Preferencias;

