import { Icon } from '../../Atoms/Icon/Icon';
import { Typography } from '../../Atoms/Typography/Typography';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { FONT_FAMILY_SANS } from '../../../designTokens';

/** Medidas de referencia Figma (escritorio). El componente usa `width: 100%` en el consumidor. */
export const TAREAS_PENDIENTES_POINT_WIDTH_PX = 542;
export const TAREAS_PENDIENTES_POINT_HEIGHT_PX = 204;

const BORDER_COLOR = '#C4C4C4';
const TEXT_COLOR = 'var(--color-cyan-19, #29474C)';

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

const statusTypographyStyle = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 400,
  fontStyle: 'normal',
  fontSize: '16px',
  lineHeight: '24px',
  letterSpacing: '0',
  color: '#0A0A0A',
  margin: 0,
};

const getCardStyle = (isCompact) => ({
  width: '100%',
  minWidth: 0,
  maxWidth: '100%',
  minHeight: isCompact ? undefined : `${TAREAS_PENDIENTES_POINT_HEIGHT_PX}px`,
  height: isCompact ? 'auto' : `${TAREAS_PENDIENTES_POINT_HEIGHT_PX}px`,
  boxSizing: 'border-box',
  borderRadius: '14px',
  border: `1px solid ${BORDER_COLOR}`,
  background: 'var(--color-white-solid, #FFFFFF)',
  opacity: 1,
  display: 'flex',
  flexDirection: 'column',
  overflow: 'hidden',
});

const formatPendingLabel = (count, template) =>
  String(template).replace(/\{count\}/g, String(count));

const StatusRow = ({
  label,
  showArrow,
  arrowIconName,
  onClick,
  href,
  to,
  linkComponent: LinkComponent,
  disabled,
  className,
  style,
}) => {
  const isInteractive = !disabled && (onClick || href || to);
  const rowStyle = {
    width: '100%',
    minWidth: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: '12px',
    border: 'none',
    background: 'transparent',
    padding: 0,
    margin: 0,
    textAlign: 'left',
    cursor: isInteractive ? 'pointer' : 'default',
    ...(style || {}),
  };

  const content = (
    <>
      <Typography component="span" variant="body-md" style={statusTypographyStyle}>
        {label}
      </Typography>
      {showArrow ? (
        <Icon
          name={arrowIconName}
          variant="24-outline"
          size={20}
          style={{ width: 20, height: 20, color: TEXT_COLOR, flexShrink: 0 }}
          aria-hidden="true"
        />
      ) : null}
    </>
  );

  if (href && !disabled) {
    return (
      <a href={href} className={className} style={{ ...rowStyle, textDecoration: 'none', color: 'inherit' }} onClick={onClick}>
        {content}
      </a>
    );
  }

  if (to && LinkComponent && !disabled) {
    return (
      <LinkComponent to={to} className={className} style={rowStyle} onClick={onClick}>
        {content}
      </LinkComponent>
    );
  }

  if (to && !disabled) {
    return (
      <a href={to} className={className} style={{ ...rowStyle, textDecoration: 'none', color: 'inherit' }} onClick={onClick}>
        {content}
      </a>
    );
  }

  if (isInteractive) {
    return (
      <button type="button" className={className} style={rowStyle} onClick={onClick} disabled={disabled}>
        {content}
      </button>
    );
  }

  return (
    <div className={className} style={rowStyle}>
      {content}
    </div>
  );
};

const ctaButtonStyle = {
  width: '100%',
  height: '48px',
  padding: '12px 16px',
  borderRadius: '8px',
  backgroundColor: '#38656D',
  border: 'none',
  boxSizing: 'border-box',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  cursor: 'pointer',
  textDecoration: 'none',
};

const ctaLabelStyle = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 400,
  fontSize: '16px',
  lineHeight: '24px',
  color: '#FFFFFF',
  textAlign: 'center',
  margin: 0,
};

/**
 * Card “Tareas pendientes” (Point): título, resumen con flecha y CTA “Ver mis tareas”.
 * Ocupa el 100% de la columna del consumidor; medidas 542×204 son referencia desktop.
 */
export const TareasPendientesPoint = ({
  title = 'Tareas pendientes',
  pendingCount = 2,
  statusTemplate = 'Tienes {count} tareas pendientes',
  statusText,
  buttonText = 'Ver mis tareas',
  showStatusArrow = true,
  statusArrowIconName = 'ChevronRightIcon',
  onViewTasksClick,
  viewTasksHref,
  viewTasksTo,
  onStatusClick,
  statusHref,
  statusTo,
  linkComponent,
  disabled = false,
  buttonDisabled,
  className = '',
  style,
  contentClassName = '',
  contentStyle,
  footerClassName = '',
  footerStyle,
  ...props
}) => {
  const resolvedStatusText = statusText ?? formatPendingLabel(pendingCount, statusTemplate);
  const isButtonDisabled = buttonDisabled ?? disabled;

  const handleViewTasks = (event) => {
    if (isButtonDisabled) {
      event?.preventDefault?.();
      return;
    }
    onViewTasksClick?.(event);
  };

  const renderCtaLabel = () => (
    <Typography component="span" variant="body-md" style={ctaLabelStyle}>
      {buttonText}
    </Typography>
  );

  const renderActionButton = () => {
    if (viewTasksHref && !isButtonDisabled) {
      return (
        <a
          href={viewTasksHref}
          className="anima-tareas-pendientes-point__cta"
          style={ctaButtonStyle}
          onClick={handleViewTasks}
        >
          {renderCtaLabel()}
        </a>
      );
    }

    if (viewTasksTo && linkComponent && !isButtonDisabled) {
      const Link = linkComponent;
      return (
        <Link
          to={viewTasksTo}
          className="anima-tareas-pendientes-point__cta"
          style={ctaButtonStyle}
          onClick={handleViewTasks}
        >
          {renderCtaLabel()}
        </Link>
      );
    }

    if (viewTasksTo && !isButtonDisabled) {
      return (
        <a
          href={viewTasksTo}
          className="anima-tareas-pendientes-point__cta"
          style={ctaButtonStyle}
          onClick={handleViewTasks}
        >
          {renderCtaLabel()}
        </a>
      );
    }

    return (
      <PrimaryActionButton
        type="button"
        fullWidth
        disabled={isButtonDisabled}
        onClick={handleViewTasks}
        className="anima-tareas-pendientes-point__cta"
      >
        {buttonText}
      </PrimaryActionButton>
    );
  };

  return (
    <article
      className={`anima-tareas-pendientes-point ${className}`.trim()}
      style={{ ...getCardStyle(false), ...(style || {}) }}
      aria-label={title}
      {...props}
    >
      <div
        className={`anima-tareas-pendientes-point__content ${contentClassName}`.trim()}
        style={{
          flex: '1 1 auto',
          minHeight: 0,
          display: 'flex',
          flexDirection: 'column',
          padding: '20px 20px 0',
          boxSizing: 'border-box',
          ...(contentStyle || {}),
        }}
      >
        <Typography component="h2" variant="body-lg" style={titleTypographyStyle}>
          {title}
        </Typography>

        <StatusRow
          className="anima-tareas-pendientes-point__status"
          style={{ marginTop: '16px' }}
          label={resolvedStatusText}
          showArrow={showStatusArrow}
          arrowIconName={statusArrowIconName}
          onClick={onStatusClick}
          href={statusHref}
          to={statusTo}
          linkComponent={linkComponent}
          disabled={disabled}
        />
      </div>

      <div
        role="presentation"
        style={{
          width: '100%',
          height: 0,
          borderTop: `1px solid ${BORDER_COLOR}`,
          flexShrink: 0,
          marginTop: 'auto',
        }}
      />

      <footer
        className={`anima-tareas-pendientes-point__footer ${footerClassName}`.trim()}
        style={{
          flexShrink: 0,
          padding: '16px 20px 20px',
          boxSizing: 'border-box',
          ...(footerStyle || {}),
        }}
      >
        {renderActionButton()}
      </footer>
    </article>
  );
};

export default TareasPendientesPoint;
