import React from "react";
import { Story, Meta } from "@storybook/react/types-6-0";

import { ThemeProvider } from "../ThemeProvider";
import FileUpload, { FileUploadProps } from "./FileUpload";

export default {
  title: "Components/Input/FileUpload",
  component: FileUpload,
} as Meta;

// https://overreacted.io/making-setinterval-declarative-with-react-hooks/
function useInterval(callback: any, delay: number | null) {
  const savedCallback = React.useRef(() => {});
  // Remember the latest callback.
  React.useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);
  // Set up the interval.
  React.useEffect((): any => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}
// useFakeProgress is an elaborate way to show a fake file transfer for illustrative purposes. You
// don't need this is your application. Use metadata from your upload destination if it's available,
// or don't provide progress.
function useFakeProgress(): [number, () => void, () => void] {
  const [fakeProgress, setFakeProgress] = React.useState(0);
  const [isActive, setIsActive] = React.useState(false);
  function stopFakeProgress() {
    setIsActive(false);
    setFakeProgress(0);
  }
  function startFakeProgress() {
    setIsActive(true);
  }
  useInterval(
    () => {
      if (fakeProgress >= 100) {
        stopFakeProgress();
      } else {
        setFakeProgress(fakeProgress + 10);
      }
    },
    isActive ? 500 : null
  );
  return [fakeProgress, startFakeProgress, stopFakeProgress];
}

const Template: Story<FileUploadProps> = (args) => {
  const [
    progressAmount,
    startFakeProgress,
    stopFakeProgress,
  ] = useFakeProgress();

  return (
    <ThemeProvider>
      <FileUpload
        {...args}
        onCancel={stopFakeProgress}
        onDrop={(acceptedFiles, rejectedFiles) => {
          // handle file upload...
          console.log(acceptedFiles, rejectedFiles);
          startFakeProgress();
        }}
        progressAmount={progressAmount}
        progressMessage={
          progressAmount ? `Uploading... ${progressAmount}% of 100%` : ""
        }
      />
    </ThemeProvider>
  );
};

export const Default = Template.bind({});
Default.args = {};
