import React, { useState } from 'react';
import moment from 'moment-timezone';
import { withDesign } from 'storybook-addon-designs';
import { action } from '@storybook/addon-actions';
import { ThemeProvider } from 'styled-components';
import at from 'lodash/at';
import map from 'lodash/map';
import min from 'lodash/min';
import keys from 'lodash/keys';

import baseTheme from '../app/themes/baseTheme';
import Button from '../app/components/elements/Button';
import ChartDateRangeModal from '../app/components/ChartDateRangeModal';

/* eslint-disable max-len */
const sleep = m => new Promise(r => setTimeout(r, m));

// Wrap each story component with the base theme
const withTheme = Story => (
  <ThemeProvider theme={baseTheme}>
    <Story />
  </ThemeProvider>
);

export default {
  title: 'Chart Date Range Modals',
  decorators: [withDesign, withTheme],
};

export const ChartDateRangeModalStory = () => {
  const [open, setOpen] = useState(true);

  const handleClickOpen = () => setOpen(true);

  const handleClose = () => {
    setOpen(false);
  };

  const [processing, setProcessing] = React.useState(false);

  const fetchedUntil = moment.utc().subtract(32, 'days').valueOf();

  const handleClickPrint = async (opts) => {
    action('Clicked Apply')(opts);
    setProcessing(true);

    // Determine the earliest startDate needed to fetch data to.
    const fetchUntil = min(at(opts, map(keys(opts), key => `${key}.endpoints.0`)));

    // If fetchUntil is earlier than the point to which we've fetched data, we need to first fetch
    // data to that date prior to generating the PDF
    if (fetchUntil < fetchedUntil) {
      action('Fetching Data for PDF')(opts);
      await sleep(2000);
    }

    action('Generating PDF')(opts);
    await sleep(1000);
    setProcessing(false);
    action('Open PDF')(opts);
  };

  const mostRecentDatumDate = moment.utc().subtract(2, 'd').valueOf();

  const defaultDates = [
    moment.utc(mostRecentDatumDate).subtract(5, 'd').valueOf(),
    mostRecentDatumDate,
  ];

  return (
    <React.Fragment>
      <Button variant="primary" onClick={handleClickOpen}>
        Open Chart Dates Dialog
      </Button>
      <ChartDateRangeModal
        defaultDates={defaultDates}
        mostRecentDatumDate={mostRecentDatumDate}
        open={open}
        onClose={handleClose}
        onSubmit={handleClickPrint}
        onDatesChange={dates => action('Updated Dates')(dates)}
        processing={processing}
        timePrefs={{
          timezoneName: 'UTC',
        }}
      />
    </React.Fragment>
  );
};

ChartDateRangeModalStory.story = {
  name: 'Chart Date Range Modal',
};

@@ -231,128 +231,8 @@
 ts';
-%0Aimport at from 'lodash/at';%0Aimport map from 'lodash/map';%0Aimport min from 'lodash/min';%0Aimport keys from 'lodash/keys';
 %0A%0Aim
@@ -1043,17 +1043,17 @@
 btract(3
-2
+0
 , 'days'
@@ -1099,22 +1099,21 @@
 = async 
-(opts)
+range
  =%3E %7B%0A  
@@ -1138,20 +1138,21 @@
 Apply')(
-opts
+range
 );%0A    s
@@ -1207,17 +1207,18 @@
 st start
-D
+ d
 ate need
@@ -1265,67 +1265,16 @@
 l = 
-min(at(opts, map(keys(opts), key =%3E %60$%7Bkey%7D.endpoints.0%60)))
+range%5B0%5D
 ;%0A%0A 
@@ -1364,71 +1364,18 @@
 to f
-irst fetch%0A    // data to that date prior to generating the PDF
+etch more.
 %0A   
@@ -1439,23 +1439,16 @@
 Data
- for PDF')(opts
+')(range
 );%0A 
@@ -1482,44 +1482,8 @@
  %7D%0A%0A
-    action('Generating PDF')(opts);%0A
     
@@ -1543,23 +1543,30 @@
 on('
-Open PDF')(opts
+Applying Dates')(range
 );%0A 

Clean up chart date range modal story handlers and actions