import styles from './ListItem.module.scss';

export interface ListItemProps {
  /** Primary text displayed in the list item */
  title: string;
  /** Secondary text displayed below the title */
  subtitle?: string;
  /** Whether to show the subtitle (default: true if subtitle is provided) */
  showSubtitle?: boolean;
  /** Content to display on the right side (e.g., count, badge) */
  trailing?: React.ReactNode;
  /** Whether this item is selected */
  selected?: boolean;
  /** Whether to show checkmark when selected (default: true) */
  showCheckmark?: boolean;
  /** Whether the item is disabled */
  disabled?: boolean;
  /** Click handler */
  onClick?: () => void;
  /** Additional CSS classes */
  className?: string;
}

const CheckIcon = ({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 9.50833 7.01458"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path
      d="M3.325 7.01458L0 3.68958L0.83125 2.85833L3.325 5.35208L8.67708 0L9.50833 0.83125L3.325 7.01458Z"
      fill={color}
    />
  </svg>
);

export const ListItem = ({
  title,
  subtitle,
  showSubtitle,
  trailing,
  selected = false,
  showCheckmark = true,
  disabled = false,
  onClick,
  className = '',
}: ListItemProps) => {
  const shouldShowSubtitle = showSubtitle ?? (subtitle !== undefined);
  const containerClassName = [
    styles.container,
    selected && styles.selected,
    disabled && styles.disabled,
    className,
  ]
    .filter(Boolean)
    .join(' ');

  const handleClick = () => {
    if (!disabled && onClick) {
      onClick();
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if ((e.key === 'Enter' || e.key === ' ') && !disabled && onClick) {
      e.preventDefault();
      onClick();
    }
  };

  return (
    <div
      className={containerClassName}
      onClick={handleClick}
      onKeyDown={handleKeyDown}
      role="option"
      aria-selected={selected}
      aria-disabled={disabled}
      tabIndex={disabled ? -1 : 0}
    >
      <div className={styles.content}>
        <span className={styles.title} title={title}>
          {title}
        </span>
        {shouldShowSubtitle && subtitle && <span className={styles.subtitle}>{subtitle}</span>}
      </div>
      {trailing && <span className={styles.trailing}>{trailing}</span>}
      {selected && showCheckmark && (
        <span className={styles.checkIcon}>
          <CheckIcon size={14} color="var(--color-primary-base)" />
        </span>
      )}
    </div>
  );
};
