// @flow
import React, { useState, useCallback } from 'react';
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: 'Components/Inputs/DateRangePicker',
  parameters: {
    docs: {
      page: docs,
    },
  },
};

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 = () => <DateRangePickerDemo />;

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

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