import { useState, useEffect, useLayoutEffect } from 'react';
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 ConfiguracionLocalizacion = ({
  // Estado de carga (skeleton)
  loading = false,
  // Título principal
  title = 'CONFIGURACIÓN DE LOCALIZACIÓN',
  titleStyle,
  titleClassName = '',
  
  // Label del desplegable (idioma predeterminado)
  labelText = 'Idioma (predeterminado)',
  labelTextStyle,
  labelTextClassName = '',
  
  // 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 = 'Zona horaria',
  labelZonaHorariaStyle,
  labelZonaHorariaClassName = '',
  zonaHorariaOptions = [],
  zonaHorariaValue = '',
  zonaHorariaOnChange,
  zonaHorariaPlaceholder = '',
  zonaHorariaDisabled = false,
  zonaHorariaClassName = '',
  zonaHorariaStyle,
  
  // Actualización (línea 1: label con icono; línea 2: texto detalle)
  actualizacionLabel = 'Última actualización:',
  actualizacionLabelStyle,
  actualizacionLabelClassName = '',
  actualizacionText = 'hace 2 horas',
  actualizacionTextStyle,
  actualizacionTextClassName = '',
  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 updateBreakpoint = () => {
    setIsNarrow(window.innerWidth <= breakpointNarrowPx);
  };

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

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

  return (
    <CardGrande
      className={`anima-configuracionlocalizacion__container ${containerClassName} ${className}`}
      style={{
        ...(isNarrow ? { minHeight: 0 } : { minHeight: '518px' }),
        ...(containerStyle || {}),
      }}
      {...props}
    >
      {/* Div padre título */}
      <div
        className={`anima-configuracionlocalizacion__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%" />
          ) : title ? (
            <Typography
              variant="body-md"
              className={titleClassName}
              style={{
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: 500,
                fontStyle: 'normal',
                fontSize: '16px',
                lineHeight: '30px',
                letterSpacing: '0%',
                verticalAlign: 'middle',
                textTransform: 'uppercase',
                color: 'var(--color-cyan-19)',
                margin: 0,
                ...(titleStyle || {}),
              }}
            >
              {title}
            </Typography>
          ) : null}
        </div>
      </div>
      
      {/* Div contenido */}
      <div
        className={`anima-configuracionlocalizacion__content ${contentContainerClassName}`}
        style={{
          width: '100%',
          flex: 1,
          ...(isNarrow ? { minHeight: 0 } : { minHeight: '460px' }),
          paddingTop: '16px',
          paddingRight: isNarrow ? '16px' : '24px',
          paddingBottom: '24px',
          paddingLeft: isNarrow ? '16px' : '24px',
          opacity: 1,
          boxSizing: 'border-box',
          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 */}
            {isNarrow ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <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 arriba - Idioma + Zona horaria */}
        <div
          style={{
            width: '100%',
            ...(isNarrow ? { minHeight: 0, paddingBottom: 0 } : { minHeight: '95px', paddingBottom: '24px' }),
            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',
            }}
          >
            {/* Desplegable: opciones las carga el proyecto consumidor (ej. llamada API) */}
            <PrimarySelect
              label={labelText}
              labelStyle={labelTextStyle}
              labelClassName={labelTextClassName}
              options={selectOptions}
              value={selectValue}
              onChange={selectOnChange}
              placeholder={selectPlaceholder}
              disabled={selectDisabled}
              className={selectClassName}
              style={selectStyle}
            />
          </div>
          
          {/* Zona horaria: label + desplegable */}
          <div
            style={{
              width: '100%',
              ...(isNarrow ? { minHeight: 0 } : { minHeight: '71px' }),
              gap: '10px',
              opacity: 1,
              boxSizing: 'border-box',
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            <PrimarySelect
              label={labelZonaHoraria}
              labelStyle={labelZonaHorariaStyle}
              labelClassName={labelZonaHorariaClassName}
              options={zonaHorariaOptions}
              value={zonaHorariaValue}
              onChange={zonaHorariaOnChange}
              placeholder={zonaHorariaPlaceholder}
              disabled={zonaHorariaDisabled}
              className={zonaHorariaClassName}
              style={zonaHorariaStyle}
            />
          </div>
        </div>
        
        {/* Última actualización + Guardar */}
        {isNarrow ? (
          <div
            style={{
              width: '100%',
              display: 'flex',
              flexDirection: 'column',
              gap: '16px',
              boxSizing: 'border-box',
              marginTop: 'auto',
            }}
          >
            <UltimaActualizacion
              variant="narrow"
              label={actualizacionLabel}
              text={actualizacionText}
              labelClassName={actualizacionLabelClassName}
              labelStyle={actualizacionLabelStyle}
              textClassName={actualizacionTextClassName}
              textStyle={actualizacionTextStyle}
            />
            <PrimaryActionButton
              text={guardarButtonText}
              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"
                label={actualizacionLabel}
                text={actualizacionText}
                labelClassName={actualizacionLabelClassName}
                labelStyle={actualizacionLabelStyle}
                textClassName={actualizacionTextClassName}
                textStyle={actualizacionTextStyle}
              />
            </div>
            <PrimaryActionButton
              text={guardarButtonText}
              disabled={guardarButtonDisabled}
              onClick={guardarButtonOnClick}
              fullWidth={false}
              className={guardarButtonClassName}
              style={guardarButtonStyle}
            />
          </div>
        )}
          </>
        )}
      </div>
    </CardGrande>
  );
};

export default ConfiguracionLocalizacion;
