import {Tooltip} from "react-tooltip";
import AppContext from "../../contexts/AppContext";
import {
    decodeHTML,
    isHomeFolder,
    removeLastFolderSession,
} from "../../includes/functions";

const {useContext, useState, useEffect, useRef, useMemo} = React;

export default function Breadcrumb() {
    const {rememberLastFolder = true} = igd.settings;

    const {
        breadcrumbs = {},
        setBreadcrumbs,
        initFolders,
        activeFolder,
        setActiveFolder,
        setActiveFile,
        listFiles,
        initParentFolder,
        show,
        isShortcodeBuilder,
        activeAccount,
        setIsOptions,
        setActiveFiles,
        shortcodeId,
    } = useContext(AppContext);

    const breadcrumbRef = useRef(null);
    const [isCollapsed, setIsCollapsed] = useState(false);
    const [isTooltipOpen, setTooltipOpen] = useState(false);

    const breadcrumbKeys = useMemo(() => Object.keys(breadcrumbs), [breadcrumbs]);

    /* ---------------------------------------------
     * Layout overflow detection
     * ------------------------------------------- */
    useEffect(() => {
        if (!breadcrumbRef.current) return;

        const el = breadcrumbRef.current;
        const header = el.closest('.igd-file-browser-header');

        const update = () => {
            setIsCollapsed(el.scrollWidth > el.clientWidth);
        };

        const observer = new ResizeObserver(update);

        observer.observe(el);
        header && observer.observe(header);

        requestAnimationFrame(update);

        return () => observer.disconnect();
    }, [breadcrumbKeys]);

    /* ---------------------------------------------
     * Derived breadcrumb groups
     * ------------------------------------------- */
    const {rootItem, collapsedItems, lastItems} = useMemo(() => {
        if (!breadcrumbKeys.length) {
            return {rootItem: "", collapsedItems: [], lastItems: []};
        }

        if (!isCollapsed) {
            return {
                rootItem: breadcrumbKeys.length > 2 ? breadcrumbKeys[0] : "",
                collapsedItems: breadcrumbKeys.length > 3 ? breadcrumbKeys.slice(1, -2) : [],
                lastItems: breadcrumbKeys.slice(-2),
            };
        }

        return {
            rootItem: "",
            collapsedItems: breadcrumbKeys.slice(0, -1),
            lastItems: [breadcrumbKeys[breadcrumbKeys.length - 1]],
        }

    }, [breadcrumbKeys, isCollapsed]);

    /* ---------------------------------------------
     * Context menu handler
     * ------------------------------------------- */
    const openContextMenu = (e) => {
        e.preventDefault();
        e.stopPropagation();

        setIsOptions(false);
        setActiveFiles([]);
        setActiveFile(activeFolder);

        show(e);
    };

    /* ---------------------------------------------
     * Render
     * ------------------------------------------- */
    return (
        <div className="igd-breadcrumb" ref={breadcrumbRef}>
            {/* Home */}
            <button
                type="button"
                className="breadcrumb-item"
                onClick={() => {
                    if (initFolders && initParentFolder) {
                        setActiveFolder(initParentFolder);
                        listFiles(initParentFolder);
                    } else {
                        setActiveFolder(null);
                    }

                    setBreadcrumbs({});
                    rememberLastFolder &&
                    removeLastFolderSession(shortcodeId);
                }}
            >
                <i className="dashicons dashicons-admin-home"/>
                <span>
                    {wp.i18n.__("Home", "integrate-google-drive")}
                </span>
            </button>

            {!!activeFolder && (
                <>
                    {/* Root */}
                    {!!rootItem && (
                        <button
                            type="button"
                            className={`breadcrumb-item ${!isShortcodeBuilder && activeFolder.id === rootItem ? "active" : ""}`}
                            onClick={(e) =>
                                activeFolder.id === rootItem
                                    ? openContextMenu(e)
                                    : listFiles({
                                        id: rootItem,
                                        name: breadcrumbs[rootItem],
                                        accountId: activeFolder.accountId,
                                        type: 'application/vnd.google-apps.folder',
                                    })
                            }
                        >
                            <span>
                                {decodeHTML(breadcrumbs[rootItem])}
                            </span>
                        </button>
                    )}

                    {/* Collapsed */}
                    {!!collapsedItems.length && (
                        <>
                            <button
                                type="button"
                                className="breadcrumb-item breadcrumb-options"
                                onClick={() =>
                                    setTooltipOpen((v) => !v)
                                }
                            >
                                <i className="dashicons dashicons-ellipsis"/>
                                <i className="dashicons dashicons-arrow-right-alt2"/>
                            </button>

                            <Tooltip
                                anchorSelect={`.breadcrumb-options`}
                                isOpen={isTooltipOpen}
                                setIsOpen={setTooltipOpen}
                                place="bottom"
                                variant="light"
                                openEvents={["click"]}
                                clickable={true}
                                className="collapsed-breadcrumbs igd-tooltip"
                                content={() =>
                                    collapsedItems.map((id) => (
                                        <div
                                            key={id}
                                            className="collapsed-breadcrumbs-item"
                                            onClick={() =>
                                                listFiles({
                                                    id,
                                                    name: breadcrumbs[id],
                                                    accountId: activeFolder.accountId,
                                                    type: 'application/vnd.google-apps.folder',
                                                })
                                            }
                                        >
                                            {decodeHTML(breadcrumbs[id])}
                                        </div>
                                    ))
                                }
                                afterShow={() => {
                                    breadcrumbRef.current.parentElement.style.zIndex = 9;
                                }}
                                afterHide={() => {
                                    breadcrumbRef.current.parentElement.style.zIndex = 2;
                                }}
                            />
                        </>
                    )}

                    {/* Last */}
                    {lastItems.map((id) => (
                        <button
                            key={id}
                            type="button"
                            className={`breadcrumb-item ${
                                !isHomeFolder(
                                    activeFolder.id,
                                    activeAccount
                                ) &&
                                !isShortcodeBuilder &&
                                activeFolder.id === id
                                    ? "active"
                                    : ""
                            }`}
                            onClick={(e) =>
                                activeFolder.id === id
                                    ? openContextMenu(e)
                                    : listFiles({
                                        id,
                                        name: breadcrumbs[id],
                                        accountId: activeFolder.accountId,
                                        type: 'application/vnd.google-apps.folder',
                                    })
                            }
                        >
                            <span>
                                {decodeHTML(breadcrumbs[id])}
                            </span>
                        </button>
                    ))}
                </>
            )}
        </div>
    );
}
