import ShortcodeBuilderContext from "../../contexts/ShortcodeBuilderContext";
import {Tooltip} from "react-tooltip";
import Sources from "./Form/Sources";
import Filters from "./Form/Filters";
import Advanced from "./Form/Advanced";
import Notifications from "./Form/Notifications";
import Permissions from "./Form/Permissions";
import {isMobile} from "../../includes/functions";

const {useState, useContext, useEffect} = React;

export default function Form() {

    const isTutorAttachmentSelector = document.querySelector('.igd-tutor-attachment-modal');

    const context = useContext(ShortcodeBuilderContext);

    const {
        editData,
        updateShortcode,
        updating,
        isEditor,
        builderType,
        isInlineSelect,
        isSelectFiles,
        isLMS,
        isWooCommerce,
        selectionType,
        isDirty,
    } = context;

    const {id, type} = editData;

    const isBrowser = 'browser' === type;
    const isUploader = 'uploader' === type;
    const isGallery = 'gallery' === type;
    const isMedia = 'media' === type;
    const isSearch = 'search' === type;
    const isEmbed = 'embed' === type;
    const isSlider = 'slider' === type;
    const isListModule = 'list' === type;

    const isEmbedConfig = isEditor && 'embed' === builderType;

    const tabs = {
        sources: wp.i18n.__('Source', "integrate-google-drive"),
        filters: wp.i18n.__('Filter', "integrate-google-drive"),
        advanced: wp.i18n.__('Advanced', "integrate-google-drive"),
        notifications: wp.i18n.__('Notifications', "integrate-google-drive"),
        permissions: wp.i18n.__('Permissions', "integrate-google-drive"),
    }

    const tabKeys = Object.keys(tabs).filter(key => {

        if ((isEmbedConfig || isWooCommerce === 'download') && ['permissions'].includes(key)) return false;

        if ((isSelectFiles || isLMS) && 'sources' !== key) return false;

        if ((isWooCommerce === 'download' || isEmbed) && ['notifications'].includes(key)) return false;

        if (isWooCommerce === 'download' && 'filters' === key) return false;

        return true;
    });

    let initTab = sessionStorage.getItem(`igd_shortcode_builder_tab_${id}`);
    if (!initTab) {
        initTab = !!id && tabKeys.includes('sources') ? 'sources' : tabKeys[0];
    }

    const [tab, setTab] = useState(initTab);
    const tabIndex = tabKeys.indexOf(tab);

    const initCollapsed = localStorage.getItem('igd_shortcode_builder_sidebar_collapsed') === 'true';
    const [isCollapsed, setCollapsed] = useState(!isMobile() && initCollapsed);

    useEffect(() => {
        if (!id) return;

        // smooth scroll to top
        const element = document.querySelector('.igd-shortcode-builder');

        if (element) {
            element.scrollIntoView({behavior: 'smooth'});
        }

        // store current tab
        sessionStorage.setItem(`igd_shortcode_builder_tab_${id}`, tab);

    }, [tab]);

    let tabTitle = wp.i18n.__('Select Files and Folders', 'integrate-google-drive');
    let tabDescription = wp.i18n.__('Select the files & folders to display in the file browser.', 'integrate-google-drive');

    if ('sources' === tab) {

        if (isUploader) {
            tabTitle = wp.i18n.__('Select Upload Folder', 'integrate-google-drive');
            tabDescription = wp.i18n.__('Select the folder where the files will be uploaded.', 'integrate-google-drive');
        }

        if (isGallery) {
            tabTitle = wp.i18n.__('Select Files and Folders', 'integrate-google-drive');
            tabDescription = wp.i18n.__('Select the files and folders to display in the gallery.', 'integrate-google-drive');
        }

        if (isMedia) {
            tabTitle = wp.i18n.__('Select Files and Folders', 'integrate-google-drive');
            tabDescription = wp.i18n.__('Select the folders and audio/ video files to display and play in the media player.', 'integrate-google-drive');
        }

        if (isSearch) {
            tabTitle = wp.i18n.__('Select Folders', 'integrate-google-drive');
            tabDescription = wp.i18n.__('Select the folders to search in.', 'integrate-google-drive');
        }

        if (isEmbed) {
            tabTitle = wp.i18n.__('Select Files', 'integrate-google-drive');
            tabDescription = wp.i18n.__('Select the files to embed. You can also select folders to embed all the files of the folder.', 'integrate-google-drive');
        }

        if (isListModule) {
            tabTitle = wp.i18n.__('Select Files', 'integrate-google-drive');
            tabDescription = wp.i18n.__('Select the files to display in the list.', 'integrate-google-drive');
        }

        if (isTutorAttachmentSelector) {
            tabTitle = wp.i18n.__('Select Files', 'integrate-google-drive');
            tabDescription = wp.i18n.__('Select the files to attach in the course.', 'integrate-google-drive');
        }

        if (isWooCommerce === 'download') {
            tabTitle = wp.i18n.__('Select Files & Folders', 'integrate-google-drive');
            tabDescription = wp.i18n.__('Select the files and folders to attach in the product for download.', 'integrate-google-drive');
        }

    }

    if ('filters' === tab) {
        tabTitle = wp.i18n.__('Filters', 'integrate-google-drive');

        if (isBrowser) {
            tabDescription = wp.i18n.__('Show/ hide files and folders and filter them by extensions and names to not display in the file browser.', 'integrate-google-drive');
        } else if (isUploader) {
            tabDescription = wp.i18n.__('Filter the files to upload by extensions', 'integrate-google-drive');
        } else if (isGallery) {
            tabDescription = wp.i18n.__('Show/ hide files and folders and filter them by extensions and names to not display in the gallery.', 'integrate-google-drive');
        } else if (isSlider) {
            tabDescription = wp.i18n.__('Show/ hide files and filter them by extensions and names to not display in the slider.', 'integrate-google-drive');
        } else if (isMedia) {
            tabDescription = wp.i18n.__('Show/ hide files and folders and filter them by extensions and names to not display in the media player.', 'integrate-google-drive');
        } else if (isSearch) {
            tabDescription = wp.i18n.__('Show/ hide files and folders and filter them by extensions and names to not display in the search results.', 'integrate-google-drive');
        }
    }

    if ('advanced' === tab) {
        tabTitle = wp.i18n.__('Advanced Options', 'integrate-google-drive');
        tabDescription = wp.i18n.__('Advanced options to customize the module.', 'integrate-google-drive');
    }

    if ('notifications' === tab) {
        tabTitle = wp.i18n.__('Email Notifications', 'integrate-google-drive');
        tabDescription = wp.i18n.__('Receive email notifications for various user activities (upload, download, delete, etc).', 'integrate-google-drive');
    }

    if ('permissions' === tab) {
        tabTitle = wp.i18n.__('Permissions', 'integrate-google-drive');
        tabDescription = wp.i18n.__('Set access permissions for the module.', 'integrate-google-drive');
    }

    return (
        <div className={`igd-shortcode-builder-form ${isEditor ? 'editor-mode' : ''}`}>

            {/* Form Tabs */}
            {!isSelectFiles && tabKeys.length > 1 &&
                <div className={`shortcode-builder-sidebar ${isCollapsed ? 'sidebar-collapsed' : ''} tab-${tab}`}>

                    {/*----- Sidebar Collapse ----*/}

                    {!isMobile() &&
                        <button
                            type={'button'}
                            className="sidebar-collapser"
                            onClick={() => {
                                setCollapsed(!isCollapsed);
                                localStorage.setItem('igd_shortcode_builder_sidebar_collapsed', !isCollapsed);
                            }}
                            title={isCollapsed ? wp.i18n.__('Expand sidebar', "integrate-google-drive") : wp.i18n.__('Collapse sidebar', "integrate-google-drive")}
                        >
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                                 xmlns="http://www.w3.org/2000/svg">
                                <path
                                    d="M4.79485 11.7282C4.95114 11.5531 5.08868 11.3781 5.24497 11.2218C7.01418 9.44633 8.78964 7.67712 10.5651 5.90165C10.7589 5.70785 10.9715 5.58282 11.2465 5.60157C11.5716 5.62658 11.8092 5.78912 11.9342 6.0892C12.0655 6.39553 12.0092 6.68936 11.7842 6.93942C11.6341 7.10822 11.4653 7.26451 11.309 7.4208C10.1212 8.60861 8.93343 9.79642 7.74562 10.9842C7.6831 11.0467 7.62059 11.0968 7.57683 11.203C7.6581 11.203 7.73937 11.203 7.82064 11.203C11.3216 11.203 14.8225 11.203 18.3234 11.203C18.9173 11.203 19.2986 11.6406 19.1798 12.1845C19.1048 12.5159 18.811 12.7722 18.4672 12.7972C18.3796 12.8034 18.2984 12.7972 18.2108 12.7972C14.7599 12.7972 11.3028 12.7972 7.8519 12.7972C7.76437 12.7972 7.6831 12.7972 7.53932 12.7972C7.62059 12.8847 7.67685 12.941 7.73312 12.9973C9.05221 14.3163 10.3713 15.6417 11.6966 16.9545C11.9217 17.1796 12.0592 17.4297 11.9905 17.7485C11.928 18.0423 11.7529 18.2611 11.4591 18.3549C11.1653 18.4487 10.8839 18.3987 10.6526 18.1798C10.3088 17.8485 9.97745 17.5109 9.63986 17.1733C8.15823 15.6917 6.67659 14.2101 5.20121 12.7284C5.05742 12.5846 4.93864 12.4284 4.79485 12.2658C4.79485 12.3283 4.79485 12.3971 4.79485 12.4721C4.79485 14.9478 4.79485 17.4234 4.79485 19.9053C4.79485 20.3492 4.60105 20.6555 4.25096 20.768C3.76333 20.9243 3.27571 20.6117 3.20069 20.0928C3.18818 20.0241 3.19443 19.9553 3.19443 19.8803C3.19443 14.6289 3.19443 9.37756 3.19443 4.12619C3.19443 3.61356 3.42574 3.30098 3.85711 3.21345C4.29472 3.12593 4.73233 3.43851 4.7886 3.88863C4.8011 3.98866 4.8011 4.08868 4.8011 4.19496C4.79485 6.70186 4.79485 9.22127 4.79485 11.7282Z"
                                    fill="currentColor"/>
                            </svg>
                        </button>
                    }


                    <div className={`shortcode-tabs ${isEditor ? 'edit-mode' : ''}`}>
                        {
                            tabKeys.map((key, i) => {

                                return (
                                    <div key={key}
                                         className={`shortcode-tab-wrap ${tabIndex >= i ? 'active' : ''}`}
                                         onClick={() => setTab(key)}>

                                        <div key={key} className={`shortcode-tab ${key}`}>
                                            <span className={`tab-icon icon-${key}`}></span>
                                            <span className="tab-name">{tabs[key]}</span>
                                        </div>

                                        {!!isCollapsed &&
                                            <Tooltip
                                                anchorSelect={`.shortcode-tab.${key}`}
                                                place="right"
                                                className={"igd-tooltip"}
                                                content={tabs[key]}
                                                delayShow={300}
                                            />
                                        }

                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
            }

            <div className="shortcode-builder-content">

                <div className="shortcode-module">

                    {!isInlineSelect && 'folders' !== selectionType && !isLMS &&
                        <div className="shortcode-module-header">

                            <div className="module-title">
                                <h2>{tabTitle}</h2>
                                <span>{tabDescription}</span>
                            </div>

                        </div>
                    }

                    {/* Sources */}
                    {'sources' === tab && <Sources/>}

                    {/* Filters */}
                    {'filters' === tab && <Filters/>}

                    {/* Advanced */}
                    {'advanced' === tab && <Advanced/>}

                    {/* Notifications */}
                    {'notifications' === tab && <Notifications/>}

                    {/* Permissions */}
                    {'permissions' === tab && <Permissions/>}
                </div>

                {/* Form Footer */}
                {!isSelectFiles && tabKeys.length > 1 &&
                    <div className="form-footer">

                        {/* Back */}
                        <button
                            data-tooltip-content={wp.i18n.__('Previous step', "integrate-google-drive")}
                            data-tooltip-id={'previous'}
                            type={'button'}
                            disabled={tabIndex === 0}
                            className={`igd-btn ${tabIndex === 0 ? 'disabled' : 'btn-link'}`}
                            onClick={() => setTab(tabKeys[tabIndex - 1])}
                        >
                            <i className={`dashicons dashicons-arrow-left-alt`}></i>
                            <span>{wp.i18n.__("Back", "integrate-google-drive")}</span>
                            <Tooltip
                                id="previous"
                                effect="solid"
                                place="top"
                                className={"igd-tooltip"}
                            />
                        </button>

                        {/* Save Changes */}
                        <button type={'button'} className={`igd-btn btn-primary ${isDirty ? '' : 'disabled'}`}
                                onClick={() => updateShortcode(editData)}>
                            {updating ? <div className="igd-spinner"></div> :
                                <i className={`dashicons dashicons-saved`}></i>}
                            <span>{isDirty ? wp.i18n.__("Save changes", "integrate-google-drive") : wp.i18n.__("Saved", "integrate-google-drive")}</span>
                        </button>

                        {/* Next Tab */}
                        <button
                            data-tooltip-content={wp.i18n.__('Next step', "integrate-google-drive")}
                            data-tooltip-id={'next'}
                            type={'button'}
                            className={`igd-btn ${tabIndex === tabKeys.length - 1 ? 'btn-primary' : 'btn-link'}`}
                            onClick={() => {
                                if (tabIndex === tabKeys.length - 1) {
                                    updateShortcode(editData, true);
                                } else {
                                    setTab(tabKeys[tabIndex + 1]);
                                }
                            }}>

                            {tabIndex === tabKeys.length - 1 ?
                                <>
                                    <i className={`dashicons dashicons-saved`}></i>
                                    <span>{wp.i18n.__("Finish", "integrate-google-drive")}</span>
                                </>
                                :
                                <>
                                    <span>{wp.i18n.__("Next", "integrate-google-drive")}</span>
                                    <i className={`dashicons dashicons-arrow-right-alt`}></i>

                                    <Tooltip
                                        id="next"
                                        effect="solid"
                                        place="top"
                                        className={"igd-tooltip"}
                                    />
                                </>
                            }

                        </button>

                    </div>
                }

            </div>
        </div>
    )
}