import { formatDate } from '@transferwise/formatting';
import { PureComponent } from 'react';
import { injectIntl, WrappedComponentProps } from 'react-intl';

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

import MonthCalendarTable from './table';

interface MonthCalendarProps extends WrappedComponentProps {
  selectedDate: Date | null;
  min: Date | null;
  max: Date | null;
  viewYear: number;
  placeholder: string;
  onSelect: () => void;
  onLabelClick: () => void;
  onViewDateUpdate: (date: { year?: number; month?: number }) => void;
}

class MonthCalendar extends PureComponent<MonthCalendarProps> {
  onMonthSelect = (month: number) => {
    this.props.onViewDateUpdate({ month });
    this.props.onSelect();
  };

  selectPreviousYear = () => {
    this.props.onViewDateUpdate({ year: this.props.viewYear - 1 });
  };

  selectNextYear = () => {
    this.props.onViewDateUpdate({ year: this.props.viewYear + 1 });
  };

  render() {
    const {
      selectedDate,
      min,
      max,
      viewYear,
      intl: { locale, formatMessage },
      placeholder,
      onLabelClick,
    } = this.props;
    return (
      <>
        <DateHeader
          dateMode={formatMessage(messages.year)}
          label={formatDate(new Date(viewYear, 0), locale, { year: 'numeric' })}
          onLabelClick={onLabelClick}
          onPreviousClick={this.selectPreviousYear}
          onNextClick={this.selectNextYear}
        />
        <MonthCalendarTable
          selectedDate={selectedDate}
          min={min}
          max={max}
          viewYear={viewYear}
          placeholder={placeholder}
          onSelect={this.onMonthSelect}
        />
      </>
    );
  }
}

export default injectIntl(MonthCalendar);
