import { useState, useEffect, useLayoutEffect } from 'react';
import { Typography } from '../../Atoms/Typography/Typography';
import { PrimaryInput } from '../../Inputs/PrimaryInput/PrimaryInput';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { IdentidadVisual } from '../IdentidadVisual/IdentidadVisual';
import { Skeleton } from '../../Atoms/Skeleton/Skeleton';
import { FONT_FAMILY_SANS, FONT_FAMILY_MONO } from '../../../designTokens';
import { CardGrande } from '../CardGrande/CardGrande';
import { UltimaActualizacion } from '../UltimaActualizacion/UltimaActualizacion';

export const ConfiguracionMarcaTenant = ({
  // Estado de carga (skeleton)
  loading = false,
  // Título principal
  title = 'CONFIGURACIÓN DE MARCA',
  titleStyle,
  titleClassName = '',
  
  // Label del input
  labelText = 'Nombre comercial',
  labelTextStyle,
  labelTextClassName = '',
  
  // Input
  inputValue = '',
  inputPlaceholder = '',
  inputOnChange,
  inputStyle,
  inputClassName = '',
  
  // Título identidad visual
  identidadVisualTitle = '',
  identidadVisualTitleStyle,
  identidadVisualTitleClassName = '',
  
  // Marca actual
  marcaActualTitle = '',
  marcaActualTitleStyle,
  marcaActualTitleClassName = '',
  marcaActualImage,
  marcaActualImageAlt = '',
  marcaActualNucleusText = '',
  marcaActualNucleusTextStyle,
  marcaActualNucleusTextClassName = '',
  
  // Formato/Upload
  formatoText = 'Formato cuadrado\nPNG de máximo 2Mb',
  formatoTextStyle,
  formatoTextClassName = '',
  uploadButtonText = 'Subir imagen',
  uploadButtonOnClick,
  uploadButtonStyle,
  uploadButtonClassName = '',
  
  // 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 = '',

  // Error de imagen (estilo Login: caja roja antes de Guardar)
  imageError = '',
  imageErrorTitle = 'La imagen seleccionada, no cumple las especificaciones.',
  imageErrorSubtitle = 'Inténtelo nuevamente.',

  // Contenedores
  containerStyle,
  containerClassName = '',
  titleContainerStyle,
  titleContainerClassName = '',
  contentContainerStyle,
  contentContainerClassName = '',
  
  // Breakpoint (resolución): narrow hasta este ancho; por defecto 1439
  breakpointNarrowPx = 1439,
  
  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-configuracionmarcatenant__container ${containerClassName} ${className}`}
      style={{
        ...(isNarrow ? { minHeight: 0 } : { minHeight: '518px' }),
        ...(containerStyle || {}),
      }}
      {...props}
    >
      {/* Div padre título */}
      <div
        className={`anima-configuracionmarcatenant__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="60%" />
          ) : 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-configuracionmarcatenant__content ${contentContainerClassName}`}
        style={{
          width: '100%',
          ...(isNarrow ? { minHeight: 0 } : { minHeight: '460px' }),
          paddingTop: '16px',
          paddingRight: isNarrow ? '16px' : '24px',
          paddingBottom: '24px',
          paddingLeft: isNarrow ? '16px' : '24px',
          opacity: 1,
          boxSizing: 'border-box',
          ...(isNarrow ? { display: 'flex', flexDirection: 'column', gap: '24px' } : {}),
          ...(contentContainerStyle || {}),
        }}
      >
        {loading ? (
          <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: '24px', boxSizing: 'border-box' }}>
            {/* Skeleton: Nombre comercial */}
            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: '10px' }}>
              <Skeleton variant="rectangular" height={21} width={140} />
              <Skeleton variant="rectangular" height={42} width="100%" />
            </div>
            {/* Skeleton: Identidad visual */}
            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: '12px' }}>
              <Skeleton variant="rectangular" height={21} width={120} />
              {isNarrow ? (
                <>
                  <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: '12px', justifyContent: 'center' }}>
                    <Skeleton variant="rectangular" height={56} width={56} style={{ borderRadius: 12 }} />
                    <Skeleton variant="rectangular" height={24} width={80} />
                  </div>
                  <div style={{ padding: 16, borderRadius: 16, backgroundColor: '#F0F3FC', display: 'flex', flexDirection: 'column', gap: 12 }}>
                    <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 12 }}>
                      <Skeleton variant="rectangular" height={48} width={48} style={{ borderRadius: 8 }} />
                      <Skeleton variant="rectangular" height={21} width="70%" />
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                      <Skeleton variant="rectangular" height={37} width={110} style={{ borderRadius: 8 }} />
                    </div>
                  </div>
                </>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'row', gap: 40, alignItems: 'flex-start' }}>
                  <div style={{ flex: '0 0 170px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, padding: 16, borderRadius: 20, backgroundColor: '#FFFFFF' }}>
                    <Skeleton variant="rectangular" height={24} width={94} />
                    <Skeleton variant="rectangular" height={72} width={72} style={{ borderRadius: 16 }} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0, padding: 20, borderRadius: 16, backgroundColor: '#F0F3FC', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
                    <Skeleton variant="rectangular" height={48} width={48} style={{ borderRadius: 8 }} />
                    <Skeleton variant="rectangular" height={42} width={135} />
                    <Skeleton variant="rectangular" height={37} width={110} style={{ borderRadius: 8 }} />
                  </div>
                </div>
              )}
            </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 }}>
                <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>
        ) : (
          <>
        {/* Div arriba - Nombre comercial */}
        <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',
            }}
          >
            {/* Div texto label */}
            {labelText && (
              <div
                style={{
                  width: '100%',
                  minHeight: '21px',
                  gap: '8px',
                  opacity: 1,
                  boxSizing: 'border-box',
                }}
              >
                <Typography
                  variant="body-sm"
                  className={labelTextClassName}
                  style={{
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 500,
                    fontStyle: 'normal',
                    fontSize: '14px',
                    lineHeight: '21px',
                    letterSpacing: '1%',
                    color: 'var(--color-main-800)',
                    margin: 0,
                    ...(labelTextStyle || {}),
                  }}
                >
                  {labelText}
                </Typography>
              </div>
            )}
            
            {/* Input: controlado si hay inputOnChange, no controlado si no (permite escribir en Storybook y cuando el padre no maneja estado) */}
            <PrimaryInput
              {...(inputOnChange
                ? { value: inputValue, onChange: inputOnChange }
                : { defaultValue: inputValue }
              )}
              placeholder={inputPlaceholder}
              className={inputClassName}
              style={inputStyle}
            />
          </div>
        </div>
        
        <IdentidadVisual
          isNarrow={isNarrow}
          identidadVisualTitle={identidadVisualTitle}
          identidadVisualTitleStyle={identidadVisualTitleStyle}
          identidadVisualTitleClassName={identidadVisualTitleClassName}
          marcaActualTitle={marcaActualTitle}
          marcaActualTitleStyle={marcaActualTitleStyle}
          marcaActualTitleClassName={marcaActualTitleClassName}
          marcaActualImage={marcaActualImage}
          marcaActualImageAlt={marcaActualImageAlt}
          marcaActualNucleusText={marcaActualNucleusText}
          marcaActualNucleusTextStyle={marcaActualNucleusTextStyle}
          marcaActualNucleusTextClassName={marcaActualNucleusTextClassName}
          formatoText={formatoText}
          formatoTextStyle={formatoTextStyle}
          formatoTextClassName={formatoTextClassName}
          uploadButtonText={uploadButtonText}
          uploadButtonOnClick={uploadButtonOnClick}
          uploadButtonStyle={uploadButtonStyle}
          uploadButtonClassName={uploadButtonClassName}
        />

        {/* Error de imagen (estilo Login) — antes del botón Guardar */}
        {imageError && (
          <div
            className="anima-configuracionmarcatenant__imageErrorBox"
            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,
              }}
            >
              {typeof imageError === 'string' ? imageError : imageErrorTitle}
            </Typography>
            <Typography
              variant="body2"
              style={{
                fontFamily: FONT_FAMILY_MONO,
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: '14px',
                lineHeight: '21px',
                letterSpacing: '0.02em',
                color: '#B30808',
                margin: 0,
              }}
            >
              {imageErrorSubtitle}
            </Typography>
          </div>
        )}

        {/* Última actualización + Guardar */}
        {isNarrow ? (
          <div
            style={{
              width: '100%',
              display: 'flex',
              flexDirection: 'column',
              gap: '16px',
              boxSizing: 'border-box',
            }}
          >
            <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',
              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 ConfiguracionMarcaTenant;

