import React, { ForwardRefRenderFunction, useEffect, useImperativeHandle, useReducer, useRef, useState } from 'react';
import { UploadManager, IFile, IUploadManagerOptions } from '@devesharp/upload-files-js';
import { useEventListener } from '../../hooks/useEventListener';
import Style from './UploadFiles.style';

interface IPropsUploadFiles extends React.ComponentProps<any> {
   drag?: boolean;
   multiple?: boolean;
   options: IUploadManagerOptions;
}

export interface IRefUploadFiles extends React.ComponentProps<any> {
   cancelFile: (file: IFile) => void;
   retryFilesError: () => void;
}

export const UploadFiles = React.forwardRef<IRefUploadFiles, IPropsUploadFiles>(function UploadFiles(
   { drag = false, multiple = false, options, children }: IPropsUploadFiles,
   ref: any,
) {
   const inputRef = useRef<any>();

   const uploadManager = useRef<UploadManager>(new UploadManager(options)).current;
   const [dragging, setDragging] = useState(false);

   function dropFile(ev: any): void {
      if (drag) {
         ev.preventDefault();
         setDragging(false);
         Array.from(ev.dataTransfer.files).forEach((file) => uploadManager.addFile(file as File));
      }
   }

   function onChangeFile(ev: any): void {
      Array.from(ev.target.files).forEach((file) => uploadManager.addFile(file as File));
      if (inputRef.current) {
         inputRef.current.value = '';
      }
   }

   useEventListener(
      'drop',
      (ev) => {
         if (!drag) {
            ev.preventDefault();
         }
      },
      inputRef,
   );

   useImperativeHandle(
      ref,
      () => ({
         cancelFile: (file: IFile) => {
            uploadManager.cancelFile(file);
         },
         retryFilesError: (file: IFile) => {
            uploadManager.retryFilesError();
         },
      }),
      [],
   );

   return (
      <Style
         onDragEnter={() => drag && setDragging(true)}
         onDragLeave={() => drag && setDragging(false)}
         onDrop={dropFile}
      >
         <input type="file" ref={inputRef} onChange={onChangeFile} multiple={multiple} />
         {children({ dragging })}
      </Style>
   );
});
