import { useState } from "react";

interface FileDropHook {
    isDragOver: boolean;
    dropAreaProps: {
        onDragOver: React.DragEventHandler;
        onDragLeave: React.DragEventHandler;
        onDrop: React.DragEventHandler;
    };
}

const useFileDrop = (onFileDrop: (files: FileList) => void): FileDropHook => {
    const [isDragOver, setIsDragOver] = useState(false);

    const handleDragOver: React.DragEventHandler = (event) => {
        event.preventDefault();
        setIsDragOver(true);
    };

    const handleDragLeave: React.DragEventHandler = () => {
        setIsDragOver(false);
    };

    const handleDrop: React.DragEventHandler = async (event) => {
        event.preventDefault();
        setIsDragOver(false);

        // const items = event.dataTransfer.items;
        // let fileList: File[] = []
        // await Array.from(items).forEach(async (itemD, index, data) => {
        //     const item: any = itemD.webkitGetAsEntry();
        //     if (item && item.isDirectory) {
        //         const directoryFiles = await getFilesFromDirectory(item);
        //         fileList.push(...directoryFiles)
        //     } else if (item && item.isFile){
        //         const file = await getFile(item as FileSystemFileEntry);
        //         fileList.push(file)
        //     }
        //     if (data.length === index + 1) {
        //         console.log('---------->', fileList)
        //         onFileDrop(fileList as any);
        //     }
        // })

        const files = event.dataTransfer.files;

        if (onFileDrop && typeof onFileDrop === 'function') {
            onFileDrop(files);
        }
    };


    const getFilesFromDirectory = async (directoryEntry: FileSystemDirectoryEntry): Promise<File[]> => {
        const fileList: File[] = [];

        const reader = directoryEntry.createReader();
        const entries = await new Promise<FileSystemEntry[]>((resolve) => {
            reader.readEntries((results) => {
                resolve(results);
            });
        });

        for (const entry of entries) {
            if (entry.isFile) {
                const file = await getFile(entry as FileSystemFileEntry);
                fileList.push(file);
            } else if (entry.isDirectory) {
                const subFiles = await getFilesFromDirectory(entry as FileSystemDirectoryEntry);
                fileList.push(...subFiles);
            }
        }

        return fileList;
    };

    const getFile = async (fileEntry: FileSystemFileEntry): Promise<File> => {
        return new Promise<File>((resolve, reject) => {
            fileEntry.file((file) => {
                resolve(file);
            }, reject);
        });
    };

    return {
        isDragOver,
        dropAreaProps: {
            onDragOver: handleDragOver,
            onDragLeave: handleDragLeave,
            onDrop: handleDrop
        },
    };
};

export default useFileDrop