import {useContext, useEffect, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {FilesContext} from "../contexts/files";
import {getFileFormatedSize, getFormatedDate} from "../../../../../../../../../../helpers";
import {handleError, handleSuccess} from "../../../../../../../../../helpers/notifications";
import confirm from "../../../../../../../../../helpers/confirm";
import {ImportDatasetFile} from "../../../../../../../../../rest/datasets";
import {DeleteFile} from "../../../../../../../../../rest/settings";

export default function FileRow({file, importProcessStarted, notifications}) {
    const {setFiles, deleting, setDeleting, importing, setImporting} = useContext(FilesContext);
    // States
    const [deletingTheFile, setDeletingTheFile] = useState(false);
    const [importingTheFile, setImportingTheFile] = useState(false);

    useEffect(() => {
        setDeletingTheFile(deleting.indexOf(file.uuid) !== -1);
        setImportingTheFile(importing.indexOf(file.uuid) !== -1);
    }, [file, deleting, importing]);

    /**
     * Delete file
     *
     * @return {Promise<void>}
     */
    const requestToDelete = async () => {
        if (!await confirm(__("Are you sure you want to delete the file?", 'limb-chatbot'))) {
            return;
        }
        setDeleting(prevState => [...prevState, file.uuid]);
        try {
            // Delete file
            await DeleteFile(LimbChatbot.rest.url, LimbChatbot.rest.nonce, 'lbaic.files.datasets', {
                uuid: file.uuid
            });
            // Succeed, delete the file
            setFiles(prevState => prevState.filter(item => item.uuid !== file.uuid));

            handleSuccess(notifications.set, {
                title: __("Deletion completed successfully.", 'limb-chatbot'),
            });
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to delete file.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Something went wrong.", 'limb-chatbot'),
            });
        }
        setDeleting(prevState => prevState.filter(id => id !== file.uuid));
    }

    /**
     * Import file
     *
     * @return {Promise<void>}
     */
    const requestToImport = async () => {
        setImporting(prevState => [...prevState, file.uuid]);
        try {
            // Start import
            const res = await ImportDatasetFile(LimbChatbot.rest.url, LimbChatbot.rest.nonce, {
                uuid: file.uuid
            });
            // Import process started
            importProcessStarted(res);
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to import file.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Something went wrong.", 'limb-chatbot'),
            });
        }
        setImporting(prevState => prevState.filter(id => id !== file.uuid));
    }

    return <tr key={file.uuid} className='lbaic-settings-e-anf-table-body-in'>
        <td className='lbaic-settings-e-anf-table-body-item lbaic-settings-e-anf-table-body-file'>
            <span className='lbaic-settings-e-anf-table-body-label lbaic-settings-e-anf-table-body-file-label'>{file.original_name}</span>
        </td>
        <td className='lbaic-settings-e-anf-table-body-item'>
            <span className='lbaic-settings-e-anf-table-body-label lbaic-settings-e-anf-table-body-file-label'>{getFileFormatedSize(file.file_size || 0)}</span>
        </td>
        <td className='lbaic-settings-e-anf-table-body-item'>
            <span className='lbaic-settings-e-anf-table-body-label lbaic-settings-e-anf-table-body-file-label'>{getFormatedDate(file.created_at, 'DD.MM.YYYY')}</span>
        </td>
        <td className='lbaic-settings-e-anf-table-body-item lbaic-settings-e-anf-table-body-remove'>
            <div className="lbaic-settings-e-anf-table-body-item-in">
                <button
                    className={`lbaic-settings-e-anf-table-body-remove-in lbaic-settings-button-reset${deletingTheFile ? ' lbaic-settings-button-disabled' : ''}`}
                    onClick={() => !deletingTheFile && requestToDelete()}>
                    {deletingTheFile ?
                        <svg className='lbaic-settings-button-i lbaic-settings-loading-circle lbaic-settings-button-loading-circle'
                             xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24'>
                            <use href='#lbaic-settings-circle'/>
                        </svg>
                        :
                        <svg className='lbaic-settings-e-anf-table-body-remove-i'
                             xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'>
                            <use href='#lbaic-settings-delete'/>
                        </svg>}
                </button>
                <button onClick={() => !importingTheFile && !importing.length && requestToImport()}
                        className={`lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-28 lbaic-settings-button-primary${importingTheFile || importing.length > 0 ? ' lbaic-settings-button-disabled' : ''}`}>
                    {importingTheFile &&
                        <svg className='lbaic-settings-button-i lbaic-settings-loading-circle'
                             xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24'>
                            <use href='#lbaic-settings-circle'/>
                        </svg>}
                    <span className='lbaic-settings-button-label'>{__("Import", 'limb-chatbot')}</span>
                </button>
            </div>
        </td>
    </tr>
}