import { Icon } from '../Atoms/Icon/Icon';
import { useViewportMaxWidth } from '../../hooks/useViewportMaxWidth';
import { FONT_FAMILY_SANS } from '../../designTokens';

const DEFAULT_ITEMS = [
  {
    id: 'actualizar-datos',
    text: 'Actualizar datos',
    icon: 'heroicons-outline/pencil-square',
  },
  {
    id: 'ultimo-recibo',
    text: 'Último recibo',
    icon: 'heroicons-outline/document-arrow-down',
  },
];

const BADGE_BG = '#E8B261';
const TEXT_COLOR = '#29474C';
const BORDER_COLOR = '#C4C4C4';
const ITEM_WIDTH_PX = 155;

/**
 * Convierte identificadores tipo `heroicons-outline/pencil-square` o `pencil-square`
 * al nombre de componente Heroicons (`PencilSquareIcon`).
 */
export const resolveAccionesPointIconName = (icon) => {
  if (!icon || typeof icon !== 'string') return null;

  const slug = icon.includes('/') ? icon.split('/').pop() : icon.replace(/Icon$/i, '');
  if (!slug) return null;

  if (slug.endsWith('Icon')) return slug;

  const pascal = slug
    .split('-')
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join('');

  return pascal ? `${pascal}Icon` : null;
};

const getParentStyle = (isCompact, { compactBackground }) => ({
  width: '100%',
  minWidth: 0,
  maxWidth: '100%',
  minHeight: isCompact ? undefined : '84px',
  boxSizing: 'border-box',
  borderRadius: isCompact ? 0 : '12px',
  border: isCompact ? 'none' : `1px solid ${BORDER_COLOR}`,
  paddingTop: isCompact ? 0 : '16px',
  paddingBottom: isCompact ? 0 : '16px',
  background: isCompact ? compactBackground : 'var(--color-white-solid, #FFFFFF)',
  opacity: 1,
});

const getRowStyle = (isCompact) => ({
  width: '100%',
  minWidth: 0,
  minHeight: isCompact ? undefined : '52px',
  boxSizing: 'border-box',
  paddingLeft: isCompact ? 0 : '20px',
  paddingRight: isCompact ? 0 : '24px',
  display: 'flex',
  alignItems: isCompact ? 'flex-start' : 'center',
  flexWrap: 'nowrap',
  opacity: 1,
});

const getItemStyle = (isCompact) =>
  isCompact
    ? {
        display: 'inline-flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'flex-start',
        gap: '10px',
        minHeight: 0,
        minWidth: 0,
        width: 'auto',
        maxWidth: 'none',
        flex: '1 1 0',
        border: 'none',
        background: 'transparent',
        padding: 0,
        margin: 0,
        cursor: 'pointer',
        textDecoration: 'none',
        color: 'inherit',
        font: 'inherit',
        opacity: 1,
      }
    : {
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'flex-start',
        gap: '10px',
        minHeight: '52px',
        minWidth: 0,
        width: `${ITEM_WIDTH_PX}px`,
        maxWidth: `${ITEM_WIDTH_PX}px`,
        flex: `0 0 ${ITEM_WIDTH_PX}px`,
        border: 'none',
        background: 'transparent',
        padding: 0,
        margin: 0,
        cursor: 'pointer',
        textDecoration: 'none',
        color: 'inherit',
        font: 'inherit',
        opacity: 1,
      };

const getLabelStyle = (isCompact, compactLabelColor) =>
  isCompact
    ? {
        fontFamily: FONT_FAMILY_SANS,
        fontWeight: 500,
        fontStyle: 'normal',
        fontSize: '14px',
        lineHeight: '21px',
        letterSpacing: '0.01em',
        textAlign: 'center',
        color: compactLabelColor,
        whiteSpace: 'normal',
        minWidth: 0,
        width: '100%',
      }
    : labelStyle;

const badgeStyle = {
  width: '52px',
  height: '52px',
  borderRadius: '16px',
  background: BADGE_BG,
  display: 'inline-flex',
  alignItems: 'center',
  justifyContent: 'center',
  flexShrink: 0,
  opacity: 1,
};

const labelStyle = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 500,
  fontStyle: 'normal',
  fontSize: '14px',
  lineHeight: '21px',
  letterSpacing: '0.01em',
  textAlign: 'left',
  color: TEXT_COLOR,
  whiteSpace: 'nowrap',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  minWidth: 0,
  flex: '1 1 auto',
};

const ActionItem = ({
  item,
  index,
  onActionClick,
  linkComponent: LinkComponent,
  isCompact,
  compactLabelColor,
}) => {
  const {
    text,
    icon,
    href,
    to,
    target,
    rel,
    onClick,
    disabled = false,
    ariaLabel,
    badgeBackground,
    iconColor = TEXT_COLOR,
    iconSize = 20,
    iconVariant = '24-outline',
  } = item ?? {};

  const iconName = resolveAccionesPointIconName(icon);
  const resolvedAriaLabel = ariaLabel ?? text ?? 'Acción';

  const content = (
    <>
      <span
        className="anima-acciones-point__badge"
        style={{
          ...badgeStyle,
          ...(badgeBackground ? { background: badgeBackground } : {}),
        }}
      >
        {iconName ? (
          <Icon
            name={iconName}
            variant={iconVariant}
            size={iconSize}
            style={{
              width: 20,
              height: 20,
              minWidth: 20,
              minHeight: 20,
              color: iconColor,
              flexShrink: 0,
              stroke: iconColor,
            }}
            aria-hidden="true"
          />
        ) : null}
      </span>
      <span
        className="anima-acciones-point__label"
        style={getLabelStyle(isCompact, compactLabelColor)}
      >
        {text}
      </span>
    </>
  );

  const sharedProps = {
    className: 'anima-acciones-point__item',
    style: {
      ...getItemStyle(isCompact),
      ...(disabled ? { cursor: 'not-allowed', opacity: 0.5 } : {}),
    },
    'aria-label': resolvedAriaLabel,
    'aria-disabled': disabled || undefined,
  };

  const handleActivate = (event) => {
    if (disabled) {
      event?.preventDefault?.();
      return;
    }
    onClick?.(item, event);
    onActionClick?.(item, event);
  };

  if (href && !disabled) {
    return (
      <a
        {...sharedProps}
        href={href}
        target={target}
        rel={rel ?? (target === '_blank' ? 'noopener noreferrer' : undefined)}
        onClick={handleActivate}
      >
        {content}
      </a>
    );
  }

  if (to && LinkComponent && !disabled) {
    return (
      <LinkComponent {...sharedProps} to={to} onClick={handleActivate}>
        {content}
      </LinkComponent>
    );
  }

  if (to && !disabled) {
    return (
      <a {...sharedProps} href={to} onClick={handleActivate}>
        {content}
      </a>
    );
  }

  return (
    <button
      {...sharedProps}
      type="button"
      disabled={disabled}
      onClick={handleActivate}
    >
      {content}
    </button>
  );
};

/**
 * Barra horizontal de acciones con badge e icono (Point).
 * Pensada para el consumidor: ítems configurables, iconos vía props (`heroicons-outline/...`)
 * y navegación con `href`, `to` + `linkComponent` (React Router) u `onActionClick`.
 */
export const AccionesPoint = ({
  items = DEFAULT_ITEMS,
  onActionClick,
  linkComponent,
  className = '',
  style,
  rowClassName = '',
  rowStyle,
  /** Desktop: `start` agrupa ítems a la izquierda; `spread` los reparte; `center` centra. */
  itemsLayout = 'start',
  /** Separación horizontal entre ítems en desktop (layout `start`). */
  itemsGap = 40,
  mobileBreakpointPx = 768,
  /** Responsive: sin tarjeta; fondo transparente para que lo pinte el host. */
  compactBackground = 'transparent',
  /** Responsive: texto bajo el ícono (ej. blanco sobre fondo oscuro del host). */
  compactLabelColor = '#FFFFFF',
  ariaLabel = 'Acciones',
  ...props
}) => {
  const isCompact = useViewportMaxWidth(mobileBreakpointPx);
  const shouldWrap = isCompact && items.length > 2;

  const desktopJustify =
    itemsLayout === 'center'
      ? 'center'
      : itemsLayout === 'spread'
        ? 'space-between'
        : 'flex-start';

  const mobileJustify = shouldWrap ? 'flex-start' : 'space-between';
  const mobileColumnGap = shouldWrap ? '16px' : '24px';

  return (
    <nav
      className={`anima-acciones-point ${isCompact ? 'anima-acciones-point--compact' : ''} ${className}`.trim()}
      style={{ ...getParentStyle(isCompact, { compactBackground }), ...(style || {}) }}
      role="toolbar"
      aria-label={ariaLabel}
      data-compact={isCompact ? 'true' : 'false'}
      {...props}
    >
      <div
        className={`anima-acciones-point__row ${rowClassName}`.trim()}
        style={{
          ...getRowStyle(isCompact),
          justifyContent: isCompact ? mobileJustify : desktopJustify,
          ...(shouldWrap
            ? {
                flexWrap: 'wrap',
                columnGap: '16px',
                rowGap: '12px',
              }
            : {
                flexWrap: 'nowrap',
                ...(isCompact
                  ? { columnGap: mobileColumnGap }
                  : {
                      columnGap: itemsLayout === 'start' ? itemsGap : undefined,
                    }),
              }),
          ...(rowStyle || {}),
        }}
      >
        {items.map((item, index) => (
          <ActionItem
            key={item?.id ?? index}
            item={item}
            index={index}
            onActionClick={onActionClick}
            linkComponent={linkComponent}
            isCompact={isCompact}
            compactLabelColor={compactLabelColor}
          />
        ))}
      </div>
    </nav>
  );
};

export default AccionesPoint;
