import { useTranslation } from 'react-i18next';
import { Typography } from '../../Atoms/Typography/Typography';
import { Icon } from '../../Atoms/Icon/Icon';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { FONT_FAMILY_SANS } from '../../../designTokens';

const defaultDateOptions = {
  weekday: 'long',
  day: '2-digit',
  month: 'long',
  year: 'numeric',
};

/** Tipografía breadcrumb fila 1 – texto sección (ej. "ADMIN SISTEMAS"): 14px Regular, 20px, letter-spacing 0% */
const BREADCRUMB_SECTION_TYPOGRAPHY = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 400,
  fontStyle: 'normal',
  fontSize: '14px',
  lineHeight: '20px',
  letterSpacing: '0%',
  verticalAlign: 'middle',
  color: 'var(--color-cyan-19)',
  opacity: 1,
};

/** Tipografía breadcrumb fila 1 – texto ítem (ej. "Tenant"): 14px Bold, 20px, letter-spacing 0% – alineado al título de abajo */
const BREADCRUMB_ITEM_TYPOGRAPHY = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 700,
  fontStyle: 'normal',
  fontSize: '14px',
  lineHeight: '20px',
  letterSpacing: '0%',
  verticalAlign: 'middle',
  color: 'var(--color-cyan-19)',
  opacity: 1,
};

const coerceDate = (value) => {
  if (!value) return null;
  if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? null : d;
};

const capitalizeFirst = (value) => {
  if (!value) return value;
  return value.charAt(0).toUpperCase() + value.slice(1);
};

/**
 * SaludoConFechaDashboard
 *
 * Encabezado de dashboard con saludo y fecha formateada (locale-aware).
 * Todas las medidas/estilos se pueden overridear por props para que el proyecto consumidor ajuste sin tocar la librería.
 */
export const SaludoConFechaDashboard = ({
  // Content
  userName,
  /** Texto del título grande (fila inferior).
   *  - En modo breadcrumb (showSaludo=false), `userName` sigue siendo el ítem breadcrumb (fila 1).
   *  - `titleText` permite que el título grande (fila 2) sea otro, pero con el estilo deseado.
   */
  titleText,
  saludo,
  date = new Date(),
  showDate = true,
  showSaludoFecha = true, // Prop para ocultar saludo y fecha manteniendo el alto
  showSaludo = true, // Prop para ocultar solo el saludo ("Hola") y sus signos, manteniendo el userName
  /** Cuando showSaludo=false querés que el título grande tome el estilo “Hola Usuario” (28px/400),
   *  pero sin mostrar el texto “Hola” (que depende de showSaludo).
   */
  useHolaStyleForTitle = false,

  // Breadcrumb / inicio (arriba del saludo)
  showInicio = true,
  inicioText,
  showInicioIcon = true,
  inicioIconName = 'ChevronRightIcon',
  inicioIconVariant = '20-solid', // heroicons "mini"
  inicioIconSize = 16,
  // Responsive behavior (<= breakpoint): centrar saludo y ocultar el resto
  responsiveBreakpointPx = 1023,
  /** Alias: ancho en px para versión mobile; si se pasa, sustituye a responsiveBreakpointPx */
  mobileBreakpointPx,
  responsiveHideInicio = true,
  responsiveHideDate = true,
  /** Control independiente para ocultar el botón breadcrumb en mobile */
  responsiveHideBreadcrumbButton = false,
  responsiveCenterGreeting = true,

  // Date formatting
  locale,
  dateOptions = defaultDateOptions,
  formatDate, // (date, { locale, dateOptions }) => string
  capitalizeDate = true,

  // Layout / styles (overrideable)
  /** Separación vertical entre breadcrumb (fila 1) y título/saludo (fila 2). */
  breadcrumbTitleGap = '24px',
  /** tono de texto: 'dark' (por defecto) o 'light' */
  textTone = 'dark',
  className = '',
  style,
  leftClassName = '',
  leftStyle,
  rightClassName = '',
  rightStyle,
  saludoFechaContainerClassName = '',
  saludoFechaContainerStyle,
  inicioContainerClassName = '',
  inicioContainerStyle,
  inicioTextClassName = '',
  inicioTextStyle,
  titleSectionStyle, // Estilos para el texto de inicio cuando showSaludo={false}
  titleSectionClassName = '', // Clase para el texto de inicio cuando showSaludo={false}
  useBreadcrumbTypography = false, // Si true y showSaludo=false: fila 1 usa tipografía breadcrumb (14px sección 400, ítem 700)
  /** Si se pasa y useBreadcrumbTypography: muestra PrimaryActionButton (primary) a la derecha de la fila inferior */
  breadcrumbButtonText = '',
  onBreadcrumbButtonClick,
  /** Controla si se muestra el botón (solo aplica cuando useBreadcrumbTypography=true y breadcrumbButtonText tiene valor). */
  showBreadcrumbButton = true,
  breadcrumbButtonClassName = '',
  breadcrumbButtonStyle,

  // Back button responsive (solo aparece en mobile / <= breakpoint)
  showBackButtonOnMobile = false,
  backButtonAriaLabel = 'Volver',
  onBackButtonClick,
  backButtonTo,
  backButtonClassName = '',
  backButtonStyle,
  inicioItemTextStyle, // Override estilos del segundo texto de la fila 1 (userName en modo breadcrumb)
  inicioItemTextClassName = '', // Override clase del segundo texto de la fila 1
  inicioIconClassName = '',
  inicioIconStyle,
  greetingClassName = '',
  greetingStyle,
  greetingPrefix,
  greetingSuffix = '!',
  nameClassName = '',
  nameStyle,
  dateTextClassName = '',
  dateTextStyle,
  ...props
}) => {
  const { t, i18n } = useTranslation();
  const resolvedSaludo = saludo ?? t('saludo.hola');
  const resolvedGreetingPrefix = greetingPrefix ?? t('saludo.greetingPrefix');
  const resolvedInicioText = inicioText ?? t('nav.home');
  const resolvedLocale = locale ?? i18n.language ?? 'es-AR';

  const resolvedDate = showDate ? coerceDate(date) : null;
  const breakpointPx = mobileBreakpointPx ?? responsiveBreakpointPx;

  const effectiveTitleText = titleText !== undefined ? titleText : userName;
  const isHolaStyle = !!useHolaStyleForTitle || showSaludo;
  const isBreadcrumbTitleWithoutHola = useBreadcrumbTypography && !showSaludo;
  // Para la variante (estilo "Hola Usuario" sin mostrar "Hola"), en responsive se requiere alineación a la izquierda.
  const effectiveResponsiveCenterGreeting = isHolaStyle ? false : responsiveCenterGreeting;
  const shouldBoldTitleMobile = !!useHolaStyleForTitle && !!useBreadcrumbTypography && !showSaludo;

  const isLightTone = textTone === 'light';
  const mainTextColor = isLightTone ? 'var(--color-neutrals-white)' : 'var(--color-cyan-19)';
  const dateTextColor = isLightTone ? 'var(--color-neutrals-white)' : undefined;

  const handleBackClick = () => {
    if (typeof onBackButtonClick === 'function') {
      onBackButtonClick();
      return;
    }
    if (backButtonTo) {
      // Sin dependencia a router; el consumidor puede pasar `backButtonTo` para navegar.
      if (typeof window !== 'undefined') {
        window.location.assign(backButtonTo);
      }
    }
  };

  let formattedDate = '';
  if (resolvedDate) {
    if (typeof formatDate === 'function') {
      formattedDate = formatDate(resolvedDate, { locale: resolvedLocale, dateOptions });
    } else {
      formattedDate = new Intl.DateTimeFormat(resolvedLocale, dateOptions).format(resolvedDate);
    }
    if (capitalizeDate) {
      formattedDate = capitalizeFirst(formattedDate);
    }
  }

  return (
    <div
      className={`w-full ${className}`}
      style={style}
      {...props}
    >
      <style>{`
        .scfd-back-button {
          display: none;
        }

        @media (max-width: ${breakpointPx}px) {
          .scfd-inicio {
            display: ${responsiveHideInicio ? 'none' : 'flex'};
          }
          .scfd-date {
            display: ${responsiveHideDate ? 'none' : 'flex'};
          }
          .scfd-breadcrumb-button {
            display: ${responsiveHideBreadcrumbButton ? 'none' : 'flex'};
          }
          .scfd-saludo-fecha {
            justify-content: ${effectiveResponsiveCenterGreeting ? 'center' : 'flex-start'};
            flex-direction: column;
            align-items: flex-start;
            gap: 12px;
            padding-left: 0;
          }
          .scfd-greeting-wrapper {
            width: 100%;
          }
          .scfd-greeting-wrapper--with-back {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: flex-start;
            gap: 16px;
          }
          .scfd-greeting {
            text-align: ${effectiveResponsiveCenterGreeting ? 'center' : 'left'};
          }

          .scfd-back-button {
            display: ${showBackButtonOnMobile ? 'flex' : 'none'};
            align-items: center;
            justify-content: center;
          }

          .scfd-greeting--bold-back-mobile {
            font-weight: 500 !important;
            letter-spacing: 0% !important;
          }
          .scfd-greeting--bold-back-mobile span {
            font-weight: 500 !important;
            letter-spacing: 0% !important;
          }
        }
      `}</style>
      {/* Grid de 2 filas:
          - Fila 1: "Inicio >" (solo izquierda)
          - Fila 2: "Hola, Nombre" (izquierda) + Fecha (derecha) alineados a la misma altura */}
      <div
        className="grid grid-cols-[minmax(0,1fr)_auto] grid-rows-[auto_auto] gap-x-4 items-center"
        style={{ padding: '0 0 0 8px', rowGap: breadcrumbTitleGap }}
      >
        {showInicio && (
          <div
            className={`scfd-inicio col-start-1 row-start-1 flex items-center gap-1 ${inicioContainerClassName}`}
            style={{
              // Mantener "Inicio" alineado al mismo borde que "Hola" (padding-left del contenedor inferior)
              
              ...(inicioContainerStyle || {}),
            }}
          >
            <Typography
              variant="body-md"
              className={showSaludo ? inicioTextClassName : `${inicioTextClassName} ${titleSectionClassName}`.trim()}
              style={{
                color: mainTextColor,
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: showSaludo ? 700 : useBreadcrumbTypography ? BREADCRUMB_SECTION_TYPOGRAPHY.fontWeight : 500,
                fontStyle: 'normal',
                fontSize: showSaludo ? '14px' : useBreadcrumbTypography ? BREADCRUMB_SECTION_TYPOGRAPHY.fontSize : '24px',
                lineHeight: showSaludo ? '20px' : useBreadcrumbTypography ? BREADCRUMB_SECTION_TYPOGRAPHY.lineHeight : '42px',
                letterSpacing: showSaludo ? '0%' : useBreadcrumbTypography ? BREADCRUMB_SECTION_TYPOGRAPHY.letterSpacing : '0%',
                verticalAlign: 'middle',
                ...(showSaludo
                  ? (inicioTextStyle || {})
                  : useBreadcrumbTypography
                    ? {
                        ...BREADCRUMB_SECTION_TYPOGRAPHY,
                        color: mainTextColor,
                        ...(titleSectionStyle || {}),
                        ...(inicioTextStyle || {}),
                      }
                    : {
                        fontFamily: FONT_FAMILY_SANS,
                        fontWeight: 500,
                        fontStyle: 'normal',
                        fontSize: '24px',
                        lineHeight: '42px',
                        letterSpacing: '0%',
                        verticalAlign: 'middle',
                        color: mainTextColor,
                        ...(titleSectionStyle || {}),
                        ...(inicioTextStyle || {}),
                      }
                ),
              }}
            >
              {resolvedInicioText}
            </Typography>
            {showInicioIcon && inicioIconName ? (
              <Icon
                name={inicioIconName}
                variant={inicioIconVariant}
                size={inicioIconSize}
                className={inicioIconClassName}
                style={{
                  color: 'var(--color-cyan-19)',
                  opacity: 1,
                  transform: 'rotate(0deg)',
                  ...(inicioIconStyle || {}),
                }}
              />
            ) : null}
            {!showSaludo && userName ? (
              <Typography
                variant="body-md"
                className={useBreadcrumbTypography ? `${inicioTextClassName} ${inicioItemTextClassName}`.trim() : inicioTextClassName}
                style={
                  useBreadcrumbTypography
                    ? {
                        ...BREADCRUMB_ITEM_TYPOGRAPHY,
                        display: 'flex',
                        color: mainTextColor,
                        ...(inicioItemTextStyle || {}),
                      }
                    : {
                        color: mainTextColor,
                        fontFamily: FONT_FAMILY_SANS,
                        fontWeight: 500,
                        fontStyle: 'normal',
                        fontSize: '24px',
                        lineHeight: '42px',
                        letterSpacing: '0%',
                        verticalAlign: 'middle',
                        ...(inicioTextStyle || {}),
                      }
                }
              >
                {userName}
              </Typography>
            ) : null}
          </div>
        )}

        {/* Contenedor padre de la fila "Hola + Fecha" (Figma) */}
        <div
          className={`scfd-saludo-fecha col-start-1 col-end-3 row-start-2 flex items-center justify-between ${saludoFechaContainerClassName}`}
          style={{
            // Responsive: ocupar el ancho disponible sin generar scroll horizontal,
            // manteniendo el ancho Figma como máximo.
            width: '100%',
            opacity: 1,
            transform: 'rotate(0deg)',
            boxSizing: 'border-box',
            visibility: showSaludoFecha ? 'visible' : 'hidden',
            marginBottom: '10px',
            ...(saludoFechaContainerStyle || {}),
          }}
        >
          <div
            className={`scfd-greeting-wrapper min-w-0 ${leftClassName} ${showBackButtonOnMobile ? 'scfd-greeting-wrapper--with-back' : ''}`}
            style={leftStyle}
          >
            {showBackButtonOnMobile ? (
              <button
                type="button"
                aria-label={backButtonAriaLabel}
                className={`scfd-back-button ${backButtonClassName}`}
                style={backButtonStyle}
                onClick={handleBackClick}
              >
                <Icon
                  name="ArrowLeftIcon"
                  variant="24-outline"
                  size={24}
                  style={{ width: 24, height: 24, color: mainTextColor }}
                />
              </button>
            ) : null}
            <Typography
              variant="h5"
              className={`scfd-greeting ${greetingClassName} ${shouldBoldTitleMobile ? 'scfd-greeting--bold-back-mobile' : ''}`}
              style={{
                color: mainTextColor,
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: isHolaStyle ? 400 : 500,
                fontStyle: 'normal',
                fontSize: isBreadcrumbTitleWithoutHola ? '24px' : (isHolaStyle ? '28px' : '24px'),
                lineHeight: '42px',
                letterSpacing: '0%',
                verticalAlign: 'middle',
                ...(greetingStyle || {}),
              }}
            >
              {showSaludo && (
                <span
                  style={{
                    display: 'inline-block',
                    verticalAlign: 'middle',
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 400,
                    fontStyle: 'normal',
                    fontSize: '28px',
                    lineHeight: '42px',
                    letterSpacing: '0%',
                    color: mainTextColor,
                  }}
                >
                  {resolvedGreetingPrefix}
                  {resolvedSaludo}
                </span>
              )}
              {effectiveTitleText ? (
                <>
                  {showSaludo && (
                    <span style={{ display: 'inline-block', verticalAlign: 'middle' }}>{',\u00A0'}</span>
                  )}
                  <span
                    className={nameClassName}
                    style={{
                      display: isHolaStyle ? 'inline-block' : 'flex',
                      verticalAlign: 'middle',
                      color: mainTextColor,
                      fontFamily: FONT_FAMILY_SANS,
                      fontWeight: isHolaStyle ? 400 : 500,
                      fontStyle: 'normal',
                      fontSize: isBreadcrumbTitleWithoutHola ? '24px' : (isHolaStyle ? '28px' : '24px'),
                      lineHeight: '42px',
                      letterSpacing: '0%',
                      ...(nameStyle || {}),
                    }}
                  >
                    {effectiveTitleText}
                  </span>
                </>
              ) : null}
              {showSaludo && (
                <span style={{ display: 'inline-block', verticalAlign: 'middle' }}>{greetingSuffix}</span>
              )}
            </Typography>
          </div>

          {showDate && formattedDate ? (
            <div className={`scfd-date flex items-center flex-shrink-0 ${rightClassName}`} style={rightStyle}>
              <Typography
                variant="body-lg"
                className={`color-gray-600 ${dateTextClassName}`}
                style={{
                  color: dateTextColor,
                  ...(dateTextStyle || {}),
                }}
              >
                {formattedDate}
              </Typography>
            </div>
          ) : null}
          {showBreadcrumbButton && useBreadcrumbTypography && breadcrumbButtonText ? (
            <div
              className={`scfd-breadcrumb-button flex items-center flex-shrink-0 ${breadcrumbButtonClassName}`}
              style={breadcrumbButtonStyle}
            >
              <PrimaryActionButton
                variant="primary"
                onClick={onBreadcrumbButtonClick}
                type="button"
              >
                <span
                  style={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: '8px',
                  }}
                >
                  <Icon
                    name="PlusCircleIcon"
                    size={20}
                    style={{ width: 20, height: 20, color: '#FFFFFF', flexShrink: 0 }}
                  />
                  <span
                    style={{
                      fontFamily: FONT_FAMILY_SANS,
                      fontWeight: 400,
                      fontSize: '16px',
                      lineHeight: '24px',
                      letterSpacing: '0%',
                      color: 'var(--color-white-solid, #FFFFFF)',
                      verticalAlign: 'middle',
                    }}
                  >
                    {breadcrumbButtonText}
                  </span>
                </span>
              </PrimaryActionButton>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
};

export default SaludoConFechaDashboard;


