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

import { MonthFormat } from '../../common';
import messages from '../DateLookup.messages';
import DateHeader from '../dateHeader';

import DayCalendarTable from './table';

interface DayCalendarProps extends WrappedComponentProps {
  selectedDate: Date | null;
  min: Date | null;
  max: Date | null;
  viewMonth: number;
  viewYear: number;
  monthFormat: `${MonthFormat}`;
  onSelect: (date: Date) => void;
  onLabelClick: () => void;
  onViewDateUpdate: (date: { month: number; year: number }) => void;
}

class DayCalendar extends PureComponent<DayCalendarProps> {
  selectPreviousMonth = () => {
    const { viewMonth, viewYear } = this.props;
    this.props.onViewDateUpdate({
      month: viewMonth <= 0 ? 11 : viewMonth - 1,
      year: viewMonth <= 0 ? viewYear - 1 : viewYear,
    });
  };

  selectNextMonth = () => {
    const { viewMonth, viewYear } = this.props;
    this.props.onViewDateUpdate({
      month: viewMonth >= 11 ? 0 : viewMonth + 1,
      year: viewMonth >= 11 ? viewYear + 1 : viewYear,
    });
  };

  render() {
    const {
      selectedDate,
      min,
      max,
      viewMonth,
      viewYear,
      intl: { locale, formatMessage },
      monthFormat,
      onLabelClick,
      onSelect,
    } = this.props;
    return (
      <>
        <DateHeader
          label={formatDate(new Date(viewYear, viewMonth), locale, {
            month: monthFormat,
            year: 'numeric',
          })}
          dateMode={formatMessage(messages.month)}
          onLabelClick={onLabelClick}
          onPreviousClick={this.selectPreviousMonth}
          onNextClick={this.selectNextMonth}
        />
        <DayCalendarTable {...{ selectedDate, min, max, viewMonth, viewYear, onSelect }} />
      </>
    );
  }
}

export default injectIntl(DayCalendar);
