import { clsx } from 'clsx';
import { useEffect, useRef } from 'react';
import { useIntl } from 'react-intl';

import messages from '../DateLookup.messages';

interface TableLinkProps {
  item: number;
  type: 'day' | 'month' | 'year';
  title?: string;
  longTitle?: string;
  active: boolean;
  disabled: boolean;
  today: boolean;
  autofocus?: boolean;
  onClick: (item: number) => void;
}

const TableLink = ({
  item,
  type,
  title,
  longTitle,
  active,
  disabled,
  today,
  autofocus,
  onClick,
}: TableLinkProps) => {
  const buttonRef = useRef<HTMLButtonElement>(null);
  const intl = useIntl();

  useEffect(() => {
    if (autofocus) {
      setTimeout(() => {
        buttonRef.current?.focus();
      }, 0);
    }
  }, [autofocus]);

  const onCalendarClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    if (!disabled) {
      onClick(item);
    }
  };

  const calculateAriaLabel = () => {
    if (active) {
      return `${longTitle || title || ''}, ${intl.formatMessage(
        messages.selected,
      )} ${intl.formatMessage(messages[type])}`;
    }
    return longTitle || title;
  };

  return (
    <button
      ref={buttonRef}
      type="button"
      className={clsx(
        `tw-date-lookup-${type}-option np-text-body-default-bold`,
        { active: !!active },
        { today: !!today },
      )}
      disabled={disabled}
      tabIndex={autofocus ? 0 : -1}
      aria-label={calculateAriaLabel()}
      aria-pressed={active}
      onClick={onCalendarClick}
    >
      {title || item}
    </button>
  );
};

export default TableLink;
