import { faker } from '@faker-js/faker';
import { action } from '@storybook/addon-actions';
import { Meta, StoryObj } from '@storybook/react';
import React, { useState } from 'react';
import { createGroups } from '../../../helpers/storybook';
import { noop } from '../../../helpers/utils';
import { FileUploadControl } from './FileUploadControl';

const groups = createGroups({
  Behavior: ['onFileSelected', 'disabled', 'inlineMode', 'name', 'id'],
  Content: [
    'accept',
    'label',
    'placeholder',
    'error',
    'tooltipContent',
    'value',
  ],
  Styling: ['className'],
});

const meta: Meta<typeof FileUploadControl> = {
  title: 'Primary Components/Form Elements/FileUpload',
  component: FileUploadControl,
  argTypes: {
    ...groups,
  },
};
export default meta;

export const Default: StoryObj<typeof FileUploadControl> = {
  args: {
    name: 'fileUpload',
    label: 'Ingest File',
    tooltipContent: faker.lorem.paragraph(2),
  },
  render: (args) =>
    React.createElement(() => {
      const [value, setValue] = useState(args.value);
      return (
        <>
          <FileUploadControl
            {...args}
            value={value}
            onFileSelected={(args) => {
              const {
                file,
                uploadStarted = noop,
                uploadProgress = noop,
                uploadCompleted = noop,
              } = args;

              action('onFileSelected')(file);
              let progress = 0;
              uploadStarted();
              const interval = setInterval(() => {
                uploadProgress((progress / file.size) * 100);
                progress += 10000;

                if (progress >= file.size) {
                  uploadCompleted();
                  clearInterval(interval);
                }
              }, 1);

              setValue(args);
            }}
          />
        </>
      );
    }),
};
