// (C) 2026 GoodData Corporation
import { useCallback, useState } from "react";
import { validateFile } from "./validateFile.js";
const toArray = (files) => {
    if (!files) {
        return [];
    }
    if (Array.isArray(files)) {
        return files;
    }
    return Array.from(files);
};
/**
 * @internal
 */
export function useFileSelection({ rules, multiple = false, onValidateFile, onFilesAccepted, onFilesRejected, } = {}) {
    const [selectedFiles, setSelectedFiles] = useState([]);
    const [rejections, setRejections] = useState([]);
    const selectFiles = useCallback((files) => {
        const filesToProcess = toArray(files);
        const acceptedFiles = [];
        const rejectedFiles = [];
        filesToProcess.forEach((file) => {
            const validation = onValidateFile ? onValidateFile(file) : validateFile(file, rules);
            if (validation.isValid) {
                acceptedFiles.push(file);
            }
            else {
                rejectedFiles.push({
                    file,
                    validation,
                });
            }
        });
        setRejections(rejectedFiles);
        setSelectedFiles((previousFiles) => {
            if (!acceptedFiles.length) {
                return previousFiles;
            }
            return multiple ? [...previousFiles, ...acceptedFiles] : [acceptedFiles[0]];
        });
        if (acceptedFiles.length) {
            onFilesAccepted?.(multiple ? acceptedFiles : [acceptedFiles[0]]);
        }
        if (rejectedFiles.length) {
            onFilesRejected?.(rejectedFiles);
        }
    }, [multiple, onFilesAccepted, onFilesRejected, onValidateFile, rules]);
    const removeFile = useCallback((file) => {
        setSelectedFiles((previousFiles) => previousFiles.filter((selectedFile) => selectedFile !== file));
    }, []);
    const clearSelection = useCallback(() => {
        setSelectedFiles([]);
        setRejections([]);
    }, []);
    return {
        selectedFiles,
        rejections,
        selectFiles,
        setSelectedFiles,
        removeFile,
        clearSelection,
    };
}
