/**
 * TEAM: frontend_infra
 *
 * @flow
 */

import * as React from "react";
import {storiesOf} from "@storybook/react";
import {text, boolean, withKnobs, select} from "@storybook/addon-knobs";
import sections from "latitude/stories/sections";
import CalendarDateInput, {
  DEFAULT_DATE_FORMAT,
} from "latitude/date/CalendarDateInput";
import {
  calendarDateToMoment,
  type CalendarDate,
  addDaysFromCalendarDate,
  utcStringToCalendarDate,
  today,
} from "latitude/date/CalendarDateType";
import moment from "moment-timezone";

const TZ_GUESS = moment.tz.guess();

const stories = storiesOf(`${sections.dataEntry}/Calendar Date Input`, module);
stories.addDecorator(withKnobs);
stories.add("CalendarDateInput", () => (
  <CalendarDateInputHoist {...getDateInputKnobs()} />
));

const getDateInputKnobs = () => ({
  dateFormatString: text("dateFormatString", DEFAULT_DATE_FORMAT),
  minDate: text("minDate", addDaysFromCalendarDate(today(TZ_GUESS), -10)),
  maxDate: text("maxDate", addDaysFromCalendarDate(today(TZ_GUESS), 10)),
  mondaysOnly: boolean("Mondays only", false),
  disabled: boolean("disabled", false),
  size: select("size", ["s", "m", "l"], "m"),
  isInvalid: boolean("isInvalid", false),
  placeholder: text("placeholder", "Starting value..."),
});

type CalendarDateWrapperState = {value: string | null, ...};

const defaultState = {
  value: moment.utc().toISOString(),
};

// eslint-disable-next-line import/prefer-default-export
export class CalendarDateInputHoist extends React.Component<
  {|...React.ElementConfig<typeof CalendarDateInput>, +mondaysOnly?: boolean|},
  CalendarDateWrapperState
> {
  constructor() {
    super();
    this.state = {
      ...defaultState,
    };
  }
  handleInputChange: (date: CalendarDate | null) => void = (
    date: CalendarDate | null
  ) => {
    if (date)
      this.setState({
        value: calendarDateToMoment(date, moment.tz.guess()).toISOString(),
      });
  };

  render(): React.Element<"div"> {
    const {mondaysOnly, ...calendarDateInputProps} = this.props;
    return (
      <div>
        <CalendarDateInput
          value={
            this.state.value
              ? utcStringToCalendarDate(this.state.value, moment.tz.guess())
              : null
          }
          onChange={this.handleInputChange}
          filterDate={
            mondaysOnly
              ? date => calendarDateToMoment(date, "UTC").isoWeekday() === 1
              : null
          }
          {...calendarDateInputProps}
        />
      </div>
    );
  }
}
