// @flow
import React, { useState, useCallback } from 'react';
import styled from 'styled-components';
import { action } from '@storybook/addon-actions';
import { DateRangePicker } from './index';
import type { DateRange } from './date-range-picker.proptypes';
import docs from './date-range-picker.mdx';

export default {
  component: DateRangePicker,
  title: 'One-off/DateRangePicker',
  parameters: {
    docs: {
      page: docs,
    },
  },
};

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);

type DateRangePickerDemoProps = {|
  range?: DateRange,
  hideAfterSelection?: boolean,
|};

const DateRangePickerDemo = (props: DateRangePickerDemoProps) => {
  const [range, setRange] = useState({
    from: props.range?.from,
    to: props.range?.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"
      hideAfterSelection={props.hideAfterSelection}
    />
  );
};

export const Normal = () => (
  <CenterDiv>
    <DateRangePickerDemo />
  </CenterDiv>
);

export const WithPreselectedRange = () => (
  <CenterDiv>
    <DateRangePickerDemo range={{ from: today, to: nextWeek }} />
  </CenterDiv>
);

export const HideAfterSelection = () => (
  <CenterDiv>
    <DateRangePickerDemo hideAfterSelection />
  </CenterDiv>
);
