import { formatDate } from '@transferwise/formatting';
import { useIntl } from 'react-intl';

import { getFocusableTime } from '../../getFocusableTime/getFocusableTime';
import TableLink from '../../tableLink';

interface YearCalendarTableProps {
  selectedDate: Date | null;
  min: Date | null;
  max: Date | null;
  viewYear: number;
  placeholder: string;
  onSelect: (year: number) => void;
}

const ROWS = 5;
const COLS = 4;
const YEAR_ONLY_FORMAT: Intl.DateTimeFormatOptions = { year: 'numeric' };

const YearCalendarTable = ({
  selectedDate,
  min,
  max,
  viewYear,
  placeholder,
  onSelect,
}: YearCalendarTableProps) => {
  const { locale } = useIntl();
  const startYear = viewYear - (viewYear % 20);
  const getLink = (year: number) => {
    return (
      <TableLink
        item={year}
        type="year"
        title={formatDate(new Date(year, 0), locale, YEAR_ONLY_FORMAT)}
        active={isActive(year)}
        disabled={isDisabled(year)}
        today={isThisYear(year)}
        autofocus={autofocusYear === year}
        onClick={onSelect}
      />
    );
  };

  const isActive = (year: number) => {
    return !!(selectedDate && year === selectedDate.getFullYear());
  };

  const isThisYear = (year: number) => {
    return year === new Date().getFullYear();
  };

  const isDisabled = (year: number) => {
    return !!((min && year < min.getFullYear()) || (max && year > max.getFullYear()));
  };

  const autofocusYear = (() => {
    const years = Array.from({ length: ROWS * COLS }, (_, index) => startYear + index);
    return getFocusableTime({ isActive, isNow: isThisYear, isDisabled, timeSpan: years });
  })();

  return (
    <table className="table table-condensed table-bordered tw-date-lookup-calendar m-b-0">
      <thead className="sr-only">
        <tr>
          <th colSpan={COLS}>{placeholder}</th>
        </tr>
      </thead>
      <tbody>
        {Array.from({ length: ROWS }, (_, rowIndex) => (
          <tr key={rowIndex}>
            {Array.from({ length: COLS }, (_, colIndex) => (
              <td key={colIndex}>{getLink(startYear + rowIndex * COLS + colIndex)}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default YearCalendarTable;
