/* eslint-disable react-hooks/rules-of-hooks */
import React, {useState} from 'react';
import {Meta, StoryObj} from '@storybook/react';
import {HuGoFile} from '@components/_HuGo/interfaces';
import {getRandomNumber} from '@shared/utils';

import {
  DEFAULT_VALID_TYPES,
  UploaderValidTypes,
} from './components/Layout/interfaces';
import {Uploader} from './index';

const meta: Meta<typeof Uploader> = {
  title: 'HuGo/Uploader',
  component: Uploader,
  argTypes: {
    buttonTitle: {control: 'text'},
    description: {control: 'text'},
    disabled: {control: 'boolean'},
    helper: {control: 'text'},
    isError: {control: 'boolean'},
    label: {control: 'text'},
    multiFiles: {control: 'boolean'},
    title: {control: 'text'},
    variant: {control: 'radio', options: ['input', 'button']},
    validTypes: {
      control: 'radio',
      options: [
        [UploaderValidTypes.Image],
        [UploaderValidTypes.Pdf],
        DEFAULT_VALID_TYPES,
      ],
    },
  },
};

type Story = StoryObj<typeof Uploader>;

export const UploaderComponent: Story = {
  args: {
    buttonTitle: '',
    description: 'Formatos permitidos: PDF, JPG o PNG hasta 50 MB',
    disabled: false,
    helper: 'Extra Help (Ex. Hasta 3 archivos)',
    isError: false,
    label: 'Label',
    multiFiles: false,
    title: 'Elija un archivo',
    variant: 'input',
    validTypes: undefined,
  },
  render: args => {
    const [files, setFiles] = useState<HuGoFile[]>([]);

    const onDeleteOrStopFile = (id: string) => {
      setFiles(prevFiles => prevFiles.filter(file => file.id !== id));
    };

    const onFinishUpload = (newFiles: HuGoFile[]) => {
      setFiles(prevFiles =>
        prevFiles.map(file => {
          if (
            !file.hasError &&
            newFiles.some(newFile => newFile.id === file.id)
          ) {
            const hasError = getRandomNumber(4) === 0;
            return {...file, isUploading: false, hasError};
          }
          return file;
        }),
      );
    };

    const onPickFiles = (newFiles: HuGoFile[]) => {
      setFiles(prevFiles => prevFiles.concat(newFiles));
      setTimeout(() => onFinishUpload(newFiles), 2500);
    };

    return (
      <Uploader
        {...args}
        files={files}
        onDeleteFile={onDeleteOrStopFile}
        onPickFiles={onPickFiles}
        onStopUpload={onDeleteOrStopFile}
      />
    );
  },
};

export default meta;
