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

import { createSandboxStory, globalScope } from '../../.storybook/components/sandbox/SandboxEditor';
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();
  },
};

export const Sandbox = createSandboxStory({
  code: `const App = () => {
  const onUploadFile = () => {
    return new Promise((resolve) => {
      setTimeout(() => resolve({ id: Math.round(Math.random() * 10000), url: '#' }), 2000);
    });
  };

  const onDeleteFile = () => {
    return new Promise((resolve) => {
      setTimeout(() => resolve(), 1000);
    });
  };

  return (
    <Field label="Upload documents">
      <UploadInput
        multiple
        onUploadFile={onUploadFile}
        onDeleteFile={onDeleteFile}
      />
    </Field>
  );
};`,
  scope: globalScope,
});

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>
  ),
];
