import {useEffect, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {FilesContext} from "./contexts/files";
import PopupContainer from "../../../../../../../popups/container";
import FileUpload from "../../../../../../../fields/file-upload";
import {handleError, handleWarning} from "../../../../../../../../helpers/notifications";
import {SUPPORTED_FILES} from "./_data";
import {GetSetting} from "../../../../../../../../rest/settings";
import FileRow from "./file-row";

export default function ImportFiles({addFile, close, notifications}) {
    const [loading, setLoading] = useState(1);
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [isFilesFetched, setIsFilesFetched] = useState(false);
    const [adding, setAdding] = useState(false);
    const [deleting, setDeleting] = useState([]);
    const [importing, setImporting] = useState([]);
    const [files, setFiles] = useState([]);

    useEffect(() => {
        fetchFiles();
    }, []);

    useEffect(() => {
        setIsDataFetched(isFilesFetched);
    }, [isFilesFetched]);

    const fetchFiles = async () => {
        setLoading(prev => prev + 1);
        try {
            const res = await GetSetting(LimbChatbot.rest.url, LimbChatbot.rest.nonce, 'lbaic.files.datasets');
            if (res?.value?.length) {
                setFiles(res.value);
            }
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to get files.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Something went wrong.", 'limb-chatbot'),
            });
        }
        setTimeout(() => {
            setIsFilesFetched(true);
            setLoading(prev => prev - 2);
        }, 200);
    }

    /**
     * Add new file
     *
     * @param {File} file New file
     */
    const newFileAttached = async (file) => {
        if (file?.size) {
            setAdding(true);
            const res = await addFile(file);
            if (res?.value?.length) {
                setFiles(res.value);
            }
            setAdding(false);
        } else {
            handleWarning({message: "File has no size."}, notifications.set, {
                title: __("Invalid file.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Please check your connection and try again.", 'limb-chatbot'),
            });
        }
    }

    /**
     * Import process started
     *
     * @param dataset
     */
    const importProcessStarted = (dataset) => {
        close(dataset);
    }

    return <PopupContainer title={__("Import", 'limb-chatbot')}
                           description={__("Add a new file or select one of the existing files to import.", 'limb-chatbot')}
                           close={close}
                           loading={loading > 0}
                           showLoadingContainer={loading > 0 && !isDataFetched}
                           bodyClassName='lbaic-settings-e-anf-popup-body'
                           footer={<>
                               <div></div>
                               <button className='lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-40 lbaic-settings-button-secondary'
                                       onClick={close}>
                                   <span className='lbaic-settings-button-label'>{__("Cancel", 'limb-chatbot')}</span>
                               </button>
                           </>}>
        {files?.length > 0 &&
            <div className='lbaic-settings-e-anf-table-wrapper lbaic-settings-scroll-hidden'>
                <div className="lbaic-settings-scroll-x">
                    <table className='lbaic-settings-e-anf-table'>
                        <thead className='lbaic-settings-e-anf-table-header'>
                        <tr className='lbaic-settings-e-anf-table-header-in'>
                            <th className='lbaic-settings-e-anf-table-header-item lbaic-settings-e-anf-table-header-file'>
                                <span className='lbaic-settings-e-anf-table-header-label'>{__("File", 'limb-chatbot')}</span>
                            </th>
                            <th className='lbaic-settings-e-anf-table-header-item'>
                                <span className='lbaic-settings-e-anf-table-header-label'>{__("Size", 'limb-chatbot')}</span>
                            </th>
                            <th colSpan='2' className='lbaic-settings-e-anf-table-header-item'>
                                <span className='lbaic-settings-e-anf-table-header-label'>{__("Uploaded", 'limb-chatbot')}</span>
                            </th>
                        </tr>
                        </thead>
                        <tbody className='lbaic-settings-e-anf-table-body'>
                        <FilesContext.Provider value={{setFiles, deleting, setDeleting, importing, setImporting}}>
                            {files.map(file =>
                                <FileRow key={file.uuid}
                                         file={file}
                                         importProcessStarted={importProcessStarted}
                                         notifications={notifications}/>)}
                        </FilesContext.Provider>
                        </tbody>
                    </table>
                </div>
            </div>}
        <div className='lbaic-settings-divider-gap-end lbaic-settings-e-anf-divider-gap-end'/>
        <FileUpload added={newFileAttached} label={__("Upload a file", 'limb-chatbot')} supportedTypes={SUPPORTED_FILES}/>
    </PopupContainer>
}