import { Icon } from '../../Atoms/Icon/Icon';
import { Skeleton } from '../../Atoms/Skeleton/Skeleton';
import { Typography } from '../../Atoms/Typography/Typography';
import { resolveAccionesPointIconName } from '../../AccionesPoint/AccionesPoint';
import { useViewportMaxWidth } from '../../../hooks/useViewportMaxWidth';
import { FONT_FAMILY_MONO, FONT_FAMILY_SANS } from '../../../designTokens';

const BORDER_COLOR = '#C4C4C4';
const TEXT_COLOR = 'var(--color-cyan-19, #29474C)';
const SUBTITLE_COLOR = 'var(--color-grey-600, #5F5F5F)';
const DOCUMENT_BADGE_BG = 'var(--color-cyan-82, #B8E2E9)';
const DEFAULT_TAG_BG = 'var(--color-info-700, #455DA2)';

export const RECIBOS_POINT_DEFAULT_SECTION_TITLE = 'Historial de documentos';

/** Filas skeleton al cargar (independiente de `items.length`). */
export const RECIBOS_POINT_SKELETON_ITEM_COUNT = 3;

export const RECIBOS_POINT_DEFAULT_ITEMS = [
  {
    id: 'recibo-febrero-2026',
    title: 'Recibo de sueldo',
    subtitle: 'Febrero 2026',
    tag: 'RECIBO',
  },
  {
    id: 'certificado-febrero-2026',
    title: 'Certificado de trabajo',
    subtitle: 'Febrero 2026',
    tag: 'CERTIFICADO',
  },
  {
    id: 'recibo-enero-2026',
    title: 'Recibo de sueldo',
    subtitle: 'Enero 2026',
    tag: 'RECIBO',
  },
];

const titleStyle = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 600,
  fontStyle: 'normal',
  fontSize: '16px',
  lineHeight: '24px',
  letterSpacing: 0,
  color: TEXT_COLOR,
  margin: 0,
};

const subtitleStyle = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 400,
  fontStyle: 'normal',
  fontSize: '14px',
  lineHeight: '21px',
  letterSpacing: 0,
  color: SUBTITLE_COLOR,
  margin: 0,
};

const sectionTitleStyle = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 400,
  fontStyle: 'normal',
  fontSize: '20px',
  lineHeight: '30px',
  letterSpacing: 0,
  color: TEXT_COLOR,
  margin: 0,
};

const tagStyle = {
  fontFamily: FONT_FAMILY_MONO,
  fontWeight: 400,
  fontStyle: 'normal',
  fontSize: '12px',
  lineHeight: '18px',
  letterSpacing: '0.02em',
  textTransform: 'uppercase',
  color: '#FFFFFF',
  margin: 0,
};

const getDocumentBadgeStyle = () => ({
  flexShrink: 0,
  alignSelf: 'flex-start',
  width: '40px',
  height: '40px',
  minWidth: '40px',
  minHeight: '40px',
  borderRadius: '12px',
  background: DOCUMENT_BADGE_BG,
  display: 'inline-flex',
  alignItems: 'center',
  justifyContent: 'center',
});

const getCardStyle = (isCompact) => ({
  width: '100%',
  maxWidth: '100%',
  minWidth: 0,
  boxSizing: 'border-box',
  borderRadius: '12px',
  border: `1px solid ${BORDER_COLOR}`,
  background: 'var(--color-white-solid, #FFFFFF)',
  padding: isCompact ? '12px 16px' : 'clamp(12px, 2vw, 16px) clamp(16px, 3vw, 20px)',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'stretch',
  gap: 0,
  minHeight: 0,
  height: 'auto',
});

const actionButtonStyle = {
  display: 'inline-flex',
  alignItems: 'center',
  justifyContent: 'center',
  width: '24px',
  height: '24px',
  minWidth: '24px',
  minHeight: '24px',
  padding: 0,
  margin: 0,
  border: 'none',
  background: 'transparent',
  cursor: 'pointer',
  color: TEXT_COLOR,
  flexShrink: 0,
};

const resolveIconName = (icon, fallback) => {
  if (!icon) return fallback;
  return resolveAccionesPointIconName(icon) || icon;
};

const ActionControl = ({
  iconName,
  ariaLabel,
  onClick,
  href,
  to,
  linkComponent: LinkComponent,
  disabled,
  className,
  style,
}) => {
  const content = (
    <Icon
      name={iconName}
      variant="24-outline"
      size={24}
      style={{ width: '24px', height: '24px', color: 'currentColor', flexShrink: 0 }}
      aria-hidden="true"
    />
  );

  const sharedStyle = {
    ...actionButtonStyle,
    ...(disabled ? { cursor: 'not-allowed', opacity: 0.5 } : {}),
    ...(style || {}),
  };

  if (href && !disabled) {
    return (
      <a href={href} className={className} style={sharedStyle} aria-label={ariaLabel} onClick={onClick}>
        {content}
      </a>
    );
  }

  if (to && LinkComponent && !disabled) {
    return (
      <LinkComponent to={to} className={className} style={sharedStyle} aria-label={ariaLabel} onClick={onClick}>
        {content}
      </LinkComponent>
    );
  }

  if (to && !disabled) {
    return (
      <a href={to} className={className} style={sharedStyle} aria-label={ariaLabel} onClick={onClick}>
        {content}
      </a>
    );
  }

  return (
    <button
      type="button"
      className={className}
      style={sharedStyle}
      aria-label={ariaLabel}
      disabled={disabled}
      onClick={onClick}
    >
      {content}
    </button>
  );
};

const ReciboItem = ({
  item,
  index,
  isCompact,
  onItemViewClick,
  onItemDownloadClick,
  linkComponent,
  showViewAction,
  showDownloadAction,
  viewIconName,
  downloadIconName,
  defaultDocumentIconName,
  viewAriaLabel,
  downloadAriaLabel,
}) => {
  const {
    id,
    title,
    subtitle,
    tag,
    tagLabel,
    tagBackground,
    documentIcon,
    documentIconColor = TEXT_COLOR,
    viewHref,
    viewTo,
    downloadHref,
    downloadTo,
    onViewClick,
    onDownloadClick,
    viewDisabled = false,
    downloadDisabled = false,
    disabled = false,
    ariaLabel,
    className = '',
    style,
  } = item ?? {};

  const resolvedTag = tagLabel ?? tag;
  const resolvedDocumentIcon = resolveIconName(documentIcon, defaultDocumentIconName);
  const isViewDisabled = disabled || viewDisabled;
  const isDownloadDisabled = disabled || downloadDisabled;

  const handleView = (event) => {
    if (isViewDisabled) {
      event?.preventDefault?.();
      return;
    }
    onViewClick?.(item, event);
    onItemViewClick?.(item, event);
  };

  const handleDownload = (event) => {
    if (isDownloadDisabled) {
      event?.preventDefault?.();
      return;
    }
    onDownloadClick?.(item, event);
    onItemDownloadClick?.(item, event);
  };

  const titleBlock = (
    <Typography
      component="h3"
      variant="body-md"
      style={{
        ...titleStyle,
        overflowWrap: 'anywhere',
        wordBreak: 'break-word',
      }}
    >
      {title}
    </Typography>
  );

  const subtitleBlock = subtitle ? (
    <Typography
      component="p"
      variant="body-sm"
      style={{
        ...subtitleStyle,
        overflowWrap: 'anywhere',
        wordBreak: 'break-word',
        flexShrink: 0,
      }}
    >
      {subtitle}
    </Typography>
  ) : null;

  const tagBlock = resolvedTag ? (
    <span
      className="anima-recibos-point__tag"
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '4px 12px',
        borderRadius: '8px',
        background: tagBackground ?? DEFAULT_TAG_BG,
        boxSizing: 'border-box',
        flexShrink: 0,
        maxWidth: '100%',
      }}
    >
      <Typography
        component="span"
        variant="caption"
        style={{
          ...tagStyle,
          overflowWrap: 'anywhere',
          wordBreak: 'break-word',
        }}
      >
        {resolvedTag}
      </Typography>
    </span>
  ) : null;

  const actionsBlock =
    showViewAction || showDownloadAction ? (
      <div
        className="anima-recibos-point__actions"
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: '0.5rem',
          flexShrink: 0,
          marginLeft: isCompact ? 0 : 'auto',
        }}
      >
        {showViewAction ? (
          <ActionControl
            className="anima-recibos-point__action anima-recibos-point__action--view"
            iconName={viewIconName}
            ariaLabel={viewAriaLabel}
            href={viewHref}
            to={viewTo}
            linkComponent={linkComponent}
            disabled={isViewDisabled}
            onClick={handleView}
          />
        ) : null}
        {showDownloadAction ? (
          <ActionControl
            className="anima-recibos-point__action anima-recibos-point__action--download"
            iconName={downloadIconName}
            ariaLabel={downloadAriaLabel}
            href={downloadHref}
            to={downloadTo}
            linkComponent={linkComponent}
            disabled={isDownloadDisabled}
            onClick={handleDownload}
          />
        ) : null}
      </div>
    ) : null;

  return (
    <article
      className={`anima-recibos-point__item ${className}`.trim()}
      style={{ ...getCardStyle(isCompact), ...(style || {}) }}
      aria-label={ariaLabel ?? title}
      data-item-id={id ?? index}
      data-compact={isCompact ? 'true' : 'false'}
    >
      <div
        className="anima-recibos-point__main"
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: isCompact ? '12px' : 'clamp(12px, 2vw, 16px)',
          width: '100%',
          minWidth: 0,
        }}
      >
        {!isCompact ? (
          <span className="anima-recibos-point__document-badge" style={getDocumentBadgeStyle()}>
            {resolvedDocumentIcon ? (
              <Icon
                name={resolvedDocumentIcon}
                variant="24-outline"
                size={20}
                style={{
                  width: '1.25rem',
                  height: '1.25rem',
                  maxWidth: '100%',
                  maxHeight: '100%',
                  color: documentIconColor,
                  flexShrink: 0,
                  stroke: documentIconColor,
                }}
                aria-hidden="true"
              />
            ) : null}
          </span>
        ) : null}

        {isCompact ? (
          <>
            <div
              className="anima-recibos-point__text"
              style={{
                flex: '1 1 auto',
                minWidth: 0,
                display: 'flex',
                flexDirection: 'column',
                gap: '6px',
              }}
            >
              {titleBlock}
            {(subtitleBlock || tagBlock) ? (
              <div
                className="anima-recibos-point__meta"
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  flexWrap: 'wrap',
                  width: '100%',
                  minWidth: 0,
                }}
              >
                {tagBlock}
                {subtitleBlock}
              </div>
            ) : null}
            </div>
            {actionsBlock}
          </>
        ) : (
          <>
            <div
              className="anima-recibos-point__text"
              style={{
                flex: '1 1 auto',
                minWidth: 0,
                display: 'flex',
                flexDirection: 'column',
                gap: '2px',
              }}
            >
              {titleBlock}
              {subtitleBlock}
            </div>
            {tagBlock}
            {actionsBlock}
          </>
        )}
      </div>
    </article>
  );
};

const ReciboItemSkeleton = ({ isCompact, showViewAction, showDownloadAction }) => {
  const actionCount = (showViewAction ? 1 : 0) + (showDownloadAction ? 1 : 0);

  return (
    <article
      className="anima-recibos-point__item anima-recibos-point__item--skeleton"
      style={getCardStyle(isCompact)}
      aria-hidden="true"
    >
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: isCompact ? '12px' : 'clamp(12px, 2vw, 16px)',
          width: '100%',
          minWidth: 0,
        }}
      >
        {!isCompact ? (
          <Skeleton
            variant="rectangular"
            width={40}
            height={40}
            className="shrink-0"
            style={{ borderRadius: '12px' }}
          />
        ) : null}

        {isCompact ? (
          <>
            <div
              style={{
                flex: '1 1 auto',
                minWidth: 0,
                display: 'flex',
                flexDirection: 'column',
                gap: '8px',
              }}
            >
              <Skeleton variant="rectangular" height={24} width="72%" />
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                <Skeleton variant="rectangular" height={26} width={72} style={{ borderRadius: '8px' }} />
                <Skeleton variant="rectangular" height={21} width={96} />
              </div>
            </div>
            {actionCount > 0 ? (
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', flexShrink: 0 }}>
                {showViewAction ? <Skeleton variant="rectangular" width={24} height={24} /> : null}
                {showDownloadAction ? <Skeleton variant="rectangular" width={24} height={24} /> : null}
              </div>
            ) : null}
          </>
        ) : (
          <>
            <div
              style={{
                flex: '1 1 auto',
                minWidth: 0,
                display: 'flex',
                flexDirection: 'column',
                gap: '4px',
              }}
            >
              <Skeleton variant="rectangular" height={24} width="65%" />
              <Skeleton variant="rectangular" height={21} width="40%" />
            </div>
            <Skeleton variant="rectangular" height={26} width={88} style={{ borderRadius: '8px', flexShrink: 0 }} />
            {actionCount > 0 ? (
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', flexShrink: 0, marginLeft: 'auto' }}>
                {showViewAction ? <Skeleton variant="rectangular" width={24} height={24} /> : null}
                {showDownloadAction ? <Skeleton variant="rectangular" width={24} height={24} /> : null}
              </div>
            ) : null}
          </>
        )}
      </div>
    </article>
  );
};

/**
 * Lista de recibos/documentos (Point): ícono, título, período, etiqueta y acciones ver/descargar.
 * Ocupa el 100% del contenedor del consumidor y se adapta al ancho disponible.
 */
export const RecibosPoint = ({
  items = [],
  /** `true`: solo skeleton (ignora cantidad y contenido de `items`). */
  loading = false,
  sectionTitle = RECIBOS_POINT_DEFAULT_SECTION_TITLE,
  showSectionTitle = true,
  sectionTitleClassName = '',
  sectionTitleStyle: sectionTitleStyleOverride,
  containerBackgroundColor,
  containerPadding = '16px',
  containerClassName = '',
  containerStyle,
  onItemViewClick,
  onItemDownloadClick,
  linkComponent,
  showViewAction = true,
  showDownloadAction = true,
  viewIconName = 'EyeIcon',
  downloadIconName = 'ArrowDownTrayIcon',
  defaultDocumentIconName = 'DocumentTextIcon',
  viewAriaLabel = 'Ver documento',
  downloadAriaLabel = 'Descargar documento',
  listGap = 12,
  mobileBreakpointPx = 768,
  className = '',
  style,
  listClassName = '',
  listStyle,
  ariaLabel,
  ...props
}) => {
  const isCompact = useViewportMaxWidth(mobileBreakpointPx);
  const resolvedAriaLabel = ariaLabel ?? sectionTitle ?? 'Recibos y documentos';
  const shouldShowTitle = showSectionTitle && sectionTitle;
  const shouldShowSkeleton = Boolean(loading);

  return (
    <section
      className={`anima-recibos-point ${shouldShowSkeleton ? 'anima-recibos-point--loading' : ''} ${className}`.trim()}
      style={{ width: '100%', maxWidth: '100%', minWidth: 0, boxSizing: 'border-box', ...(style || {}) }}
      aria-label={resolvedAriaLabel}
      aria-busy={shouldShowSkeleton || undefined}
      data-compact={isCompact ? 'true' : 'false'}
      data-loading={shouldShowSkeleton ? 'true' : 'false'}
      {...props}
    >
      <div
        className={`anima-recibos-point__container ${containerClassName}`.trim()}
        style={{
          width: '100%',
          maxWidth: '100%',
          minWidth: 0,
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          gap: '12px',
          ...(containerBackgroundColor != null && containerBackgroundColor !== ''
            ? { backgroundColor: containerBackgroundColor }
            : {}),
          ...(containerPadding != null && containerPadding !== ''
            ? { padding: containerPadding }
            : {}),
          ...(containerStyle || {}),
        }}
      >
        {shouldShowTitle ? (
          shouldShowSkeleton ? (
            <Skeleton
              variant="rectangular"
              height={30}
              width={220}
              className={`anima-recibos-point__section-title-skeleton ${sectionTitleClassName}`.trim()}
              style={sectionTitleStyleOverride}
            />
          ) : (
            <Typography
              component="h2"
              variant="body-lg"
              className={`anima-recibos-point__section-title ${sectionTitleClassName}`.trim()}
              style={{
                ...sectionTitleStyle,
                ...(sectionTitleStyleOverride || {}),
              }}
            >
              {sectionTitle}
            </Typography>
          )
        ) : null}

        <ul
          className={`anima-recibos-point__list ${listClassName}`.trim()}
          style={{
            listStyle: 'none',
            margin: 0,
            padding: 0,
            width: '100%',
            maxWidth: '100%',
            minWidth: 0,
            display: 'flex',
            flexDirection: 'column',
            gap: `${listGap}px`,
            boxSizing: 'border-box',
            ...(listStyle || {}),
          }}
        >
          {shouldShowSkeleton
            ? Array.from({ length: RECIBOS_POINT_SKELETON_ITEM_COUNT }, (_, index) => (
                <li
                  key={`skeleton-${index}`}
                  className="anima-recibos-point__list-item anima-recibos-point__list-item--skeleton"
                  style={{ width: '100%', minWidth: 0 }}
                >
                  <ReciboItemSkeleton
                    isCompact={isCompact}
                    showViewAction={showViewAction}
                    showDownloadAction={showDownloadAction}
                  />
                </li>
              ))
            : items.map((item, index) => (
                <li key={item?.id ?? index} className="anima-recibos-point__list-item" style={{ width: '100%', minWidth: 0 }}>
                  <ReciboItem
                    item={item}
                    index={index}
                    isCompact={isCompact}
                    onItemViewClick={onItemViewClick}
                    onItemDownloadClick={onItemDownloadClick}
                    linkComponent={linkComponent}
                    showViewAction={showViewAction}
                    showDownloadAction={showDownloadAction}
                    viewIconName={viewIconName}
                    downloadIconName={downloadIconName}
                    defaultDocumentIconName={defaultDocumentIconName}
                    viewAriaLabel={viewAriaLabel}
                    downloadAriaLabel={downloadAriaLabel}
                  />
                </li>
              ))}
        </ul>
      </div>
    </section>
  );
};

export default RecibosPoint;
