// @flow
import React, { useState, useCallback } from 'react';
import styled from 'styled-components';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { withInfo } from '@storybook/addon-info';

import { DateRangePicker } from './index';
import type { DateRange } from './date-range-picker.proptypes';
import { configDocs } from '../../../.storybook/config-docs';
import docs from './DATE_RANGE_PICKER.mkd';

const CenterDiv = styled.div`
  display: flex;
  justify-content: center;
  padding-bottom: 300px;
  padding-top: 30px;
`;

const today = new Date();
const nextWeek = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000);

const DateRangePickerDemo = (props: DateRange) => {
  const [range, setRange] = useState({ from: props.from, to: props.to });
  const handleDateSelect = useCallback(({ from, to }: DateRange) => {
    setRange({ from, to });

    if (!from && !to) {
      action('Selected Date')('from: undefined, to: undefined');
    }

    if (from && !to) {
      action('Selected Date')(`from: ${from.toString()}, to: undefined`);
    }

    if (from && to) {
      action('Selected Date')(`from: ${from.toString()}, to: ${to.toString()}`);
    }
  }, []);

  return (
    <DateRangePicker
      range={range}
      onRangeChange={handleDateSelect}
      placeholder="Enter Date Range"
      {...props}
    />
  );
};

storiesOf('One-off/DateRangePicker', module)
  .addDecorator(withInfo(configDocs(docs, DateRangePicker)))

  .add('normal', () => (
    <CenterDiv>
      <DateRangePickerDemo />
    </CenterDiv>
  ))
  .add('with preselected range', () => (
    <CenterDiv>
      <DateRangePickerDemo range={{ from: today, to: nextWeek }} />
    </CenterDiv>
  ))
  .add('hide after selection', () => (
    <CenterDiv>
      <DateRangePickerDemo hideAfterSelection />
    </CenterDiv>
  ));
