import { StoryFn, Meta } from '@storybook/react-webpack5';

import { Field } from '../field/Field';

import UploadInput, { UploadInputProps } from './UploadInput';
import { UploadResponse } from './types';

const meta: Meta<typeof UploadInput> = {
  title: 'Forms/UploadInput',
  component: UploadInput,
};

export default meta;
type Story = StoryFn<UploadInputProps>;

const createDelayedPromise = async ({
  successful = true,
  delaySeconds = 3,
  response = { id: Math.round(Math.random() * 10000), url: '#' },
}: {
  successful?: boolean;
  delaySeconds?: number;
  response?: UploadResponse;
} = {}): Promise<UploadResponse> =>
  new Promise((resolve, reject) => {
    setTimeout(
      () => (successful ? resolve(response) : reject(new Error('Unexpected error'))),
      delaySeconds * 1000,
    );
  });

const props = {
  onUploadFile: async () => {
    return createDelayedPromise();
  },
  onDeleteFile: async () => {
    return createDelayedPromise();
  },
};

const Template: Story = (args: UploadInputProps) => <UploadInput {...args} />;

export const SingleFile: Story = Template.bind({});
SingleFile.args = { ...props };

export const MultipleFiles: Story = Template.bind({});
MultipleFiles.args = { ...props, multiple: true };

export const WithinField: Story = Template.bind({});
WithinField.decorators = [
  (Story) => (
    <Field message="Something went wrong" sentiment="negative">
      <Story />
    </Field>
  ),
];
