import {createPortal, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import FileUpload from "../../../fields/file-upload";
import {handleWarning} from "../../../../helpers/notifications";
import {getFileFormatedSize, getFormatedTimestamp} from "../../../../../helpers";
import {SUPPORTED_FILES} from "./data";

export default function AddNewFile({type, files, added, deleted, close, notifications}) {
    // Actions state
    const [saving, setSaving] = useState(false);
    // Data
    const [newFiles, setNewFiles] = useState([]);
    const [deletedFilesIds, setDeletedFilesIds] = useState([]);

    /**
     * Add new file
     *
     * @param {File} file New file
     */
    const newFileAttached = (file) => {
        if (file?.size) {
            setNewFiles(prev => [
                file,
                ...prev
            ]);
        } else {
            handleWarning({message: "File has no size."}, notifications.set, {
                title: __("Failed to retrieve code interpreter files data.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Please check your connection and try again.", 'limb-chatbot'),
            });
        }
    }

    /**
     * Delete file
     *
     * @param {string} fileId File ID
     * @param {string} vectorStoreId Vector store ID
     * @return {Promise<void>}
     */
    const deleteFile = async (fileId, vectorStoreId) => {
        const result = await deleted(fileId, vectorStoreId);
        if (result) {
            setDeletedFilesIds(prev => [...prev, fileId]);
        }
    }

    /**
     * Save
     *
     * @return {Promise<void>}
     */
    const save = async () => {
        if (newFiles.length) {
            setSaving(true);
            // Get vector store to attach
            const vectorStores = Object.keys(files);
            const vectorStoreId = vectorStores?.length ? vectorStores[0] : false;
            // Add files
            const res = await added(newFiles.reverse(), vectorStoreId);
            setSaving(false);
            // Close if done
            if (res) {
                setNewFiles([]);
                setDeletedFilesIds([]);
                close();
            }
        } else {
            close();
        }
    }

    /**
     * Render new added files
     *
     * @param {File} file File
     * @return {JSX.Element}
     */
    const renderNewFile = (file) => {
        return <tr key={file.name + file.size} 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.name}</span>
            </td>
            <td className='lbaic-settings-e-anf-table-body-item'>
                <span className='lbaic-settings-e-anf-table-body-label'>{getFileFormatedSize(file.size)}</span>
            </td>
            <td className='lbaic-settings-e-anf-table-body-item'>
                <span className='lbaic-settings-e-anf-table-body-label'>{__("Not yet", 'limb-chatbot')}</span>
            </td>
            <td className='lbaic-settings-e-anf-table-body-item lbaic-settings-e-anf-table-body-remove'>
                <button className='lbaic-settings-e-anf-table-body-remove-in lbaic-settings-button-reset'
                        onClick={() => setNewFiles(newFiles.filter(item => item.name !== file.name && item.size !== file.size))}>
                    <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>
            </td>
        </tr>
    }

    /**
     * Render file
     *
     * @param {VectorStoreFile} file File
     * @param {string} vectorStoreId Vector store ID
     * @return {JSX.Element}
     */
    const renderFile = (file, vectorStoreId) => {
        return <tr key={file.id} 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.filename}</span>
            </td>
            <td className='lbaic-settings-e-anf-table-body-item'>
                <span className='lbaic-settings-e-anf-table-body-label'>{getFileFormatedSize(file.bytes)}</span>
            </td>
            <td className='lbaic-settings-e-anf-table-body-item'>
                <span className='lbaic-settings-e-anf-table-body-label'>{getFormatedTimestamp(file.created_at * 1000, 'DD.MM.YYYY')}</span>
            </td>
            <td className='lbaic-settings-e-anf-table-body-item lbaic-settings-e-anf-table-body-remove'>
                <button className='lbaic-settings-e-anf-table-body-remove-in lbaic-settings-button-reset'
                        onClick={() => deleteFile(file.id, vectorStoreId)}>
                    <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>
            </td>
        </tr>
    }

    return createPortal(<div className='lbaic-settings-popup-layout'>
        <div className='lbaic-settings-popup-overlay' onClick={close}/>
        <div className='lbaic-settings-popup'>
            <div className='lbaic-settings-e-anf-popup'>
                <div className='lbaic-settings-e-anf'>
                    <div className='lbaic-settings-e-anf-header'>
                        <div className='lbaic-settings-e-anf-header-in'>
                            <h6 className='lbaic-settings-e-anf-header-label'>{__("Add new file", 'limb-chatbot')}</h6>
                            <p className='lbaic-settings-e-anf-header-desc'>{__("Select any text format documents.", 'limb-chatbot')}</p>
                        </div>
                        <div className='lbaic-settings-divider'/>
                    </div>
                    <div className='lbaic-settings-e-anf-body'>
                        <div className='lbaic-settings-e-anf-body-in'>
                            <div className='lbaic-settings-e-anf-table-wrapper lbaic-settings-scroll-hidden'>
                                <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'>
                                    {newFiles.map(renderNewFile)}
                                    {type === 'file_search' ?
                                        Object.entries(files).map(([vectorStoreId, vectorStoreFiles]) => vectorStoreFiles.filter(file => deletedFilesIds.indexOf(file.id) === -1).map((file) => renderFile(file, vectorStoreId)))
                                        :
                                        files.filter(file => deletedFilesIds.indexOf(file.id) === -1).map(renderFile)
                                    }
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <FileUpload added={newFileAttached} label={__("Upload a file", 'limb-chatbot')}
                                    supportedTypes={SUPPORTED_FILES[type]}/>
                    </div>
                    <div className='lbaic-settings-e-anf-footer'>
                        <button onClick={save}
                                className={`lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-40 lbaic-settings-button-primary${saving ? ' lbaic-settings-button-disabled' : ''}`}>
                            {saving &&
                                <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>}
                            <span className='lbaic-settings-button-label'>{__("Save", 'limb-chatbot')}</span>
                        </button>
                        <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>
                    </div>
                </div>
            </div>
        </div>
    </div>, document.getElementById('lbaic-settings-popup'))
}