import { Tooltip } from "react-tooltip";
import { useMounted } from "../../includes/functions";
import Appearance from "./Appearance";

const {
    __experimentalRadioGroup: RadioGroup,
    __experimentalRadio: Radio,
} = wp.components;

const { useState, useEffect } = React;

const {
    toolbar = true,
    tools = ['appearance', 'typography', 'print', 'scroll', 'fullScreen'],
    theme: savedTheme = 'system',
    fontSize: savedFontSize = 1,
    fontFamily: savedFontFamily = 'System',
    contentWidth: savedContentWidth = 'medium',
} = dracula.settings;

const toolbarTools = [
    {
        label: wp.i18n.__('Appearance', 'dracula-dark-mode'),
        icon: 'dashicons dashicons-admin-appearance',
        key: 'appearance',
    },
    {
        label: wp.i18n.__('Print', 'dracula-dark-mode'),
        icon: 'dashicons dashicons-printer',
        key: 'print',
    },
    {
        label: wp.i18n.__('Table of Contents', 'dracula-dark-mode'),
        icon: 'dashicons dashicons-list-view',
        key: 'toc',
    },
    {
        label: wp.i18n.__('Links', 'dracula-dark-mode'),
        icon: 'dashicons dashicons-admin-links',
        key: 'links',
    },
    {
        label: wp.i18n.__('Auto Scroll', 'dracula-dark-mode'),
        icon: 'dashicons dashicons-admin-settings',
        key: 'scroll',
    },
    {
        label: wp.i18n.__('Full-Screen', 'dracula-dark-mode'),
        icon: 'dashicons dashicons-editor-expand',
        key: 'fullScreen',
    },
];

const $ = jQuery;

export default function Tools() {

    const [isLoading, setIsLoading] = useState(false);
    const [isFullscreen, setIsFullscreen] = useState(false);
    const [isLinksOpen, setIsLinksOpen] = useState(false);
    const [isTocOpen, setIsTocOpen] = useState(false);

    const [isScrollActive, setIsScrollActive] = useState(false);
    const [scrollSpeed, setScrollSpeed] = useState("50");

    const [isAppearanceActive, setIsAppearanceActive] = useState(false);

    console.log('is appearance active', isAppearanceActive);

    const isMounted = useMounted();

    const parentTheme = window.parent.draculaMode;

    const [data, setData] = useState({
        contentWidth: localStorage.getItem("reading-mode-content-width") || savedContentWidth,
        theme: parentTheme || localStorage.getItem("reading-mode-theme") || savedTheme,
        fontFamily: localStorage.getItem("reading-mode-font-family") || savedFontFamily,
        fontSize: localStorage.getItem("reading-mode-font-size") || savedFontSize,
    });

    const handleClose = (e) => {
        const isIframe = window.top !== window.self;
        const isFullScreen = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;

        // Tooltip.hide();

        if (isIframe) {
            $('.reading-mode-iframe', parent.document).removeClass('active');
            $('body', parent.document).removeClass('reading-mode-enabled');

            // check full screen & exit full 
            if (isFullScreen) {
                setIsFullscreen(false);

                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
            }
        } else {
            window.location.href = $('.site-url').attr('href');
        }
    }

    const handleFullScreen = () => {
        const isFullScreen = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;
        if (isFullScreen) {
            setIsFullscreen(false);

            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            }

        } else {
            setIsFullscreen(true);

            const element = document.documentElement;
            if (element.requestFullscreen) {
                element.requestFullscreen();
            } else if (element.mozRequestFullScreen) {
                element.mozRequestFullScreen();
            } else if (element.webkitRequestFullscreen) {
                element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
            }
        }
    }

    const handleTOC = () => {
        if (isTocOpen) {
            setIsTocOpen(false);
            $('#reading-mode-toc').empty();
        } else {
            setIsTocOpen(true);
            $('.reading-mode-body').createTOC({
                title: "Table of Contents",
                insert: "#reading-mode-toc",
            });
        }
    }

    const handleLinks = () => {
        if (isLinksOpen) {
            setIsLinksOpen(false);
            $('#reading-mode-links').empty();
        } else {
            setIsLinksOpen(true);
            $('.reading-mode-body').createTOC({
                title: "Links",
                insert: "#reading-mode-links",
                selector: 'a',
            });
        }
    }

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

        function pageScroll() {
            clearTimeout(window.scrolldelay);

            window.scrollBy(0, 1);

            window.scrolldelay = setTimeout(pageScroll, parseInt(scrollSpeed));
        }

        if (isScrollActive) {
            pageScroll();
        } else {
            clearTimeout(window.scrolldelay);
        }

    }, [isScrollActive, scrollSpeed]);

    const { contentWidth, theme, fontFamily, fontSize, } = data;

    // Handle theme change
    useEffect(() => {
        if (!isMounted) return;

        if ('dark' === theme) {
            draculaDarkMode.enable();
        } else if ('system' === theme) {
            draculaDarkMode.auto();
        } else {
            draculaDarkMode.disable();
        }

    }, [theme]);

    // Handle width change
    useEffect(() => {
        $('.reading-mode').removeClass('width-small width-medium width-large width-full').addClass(`width-${contentWidth}`);
    }, [contentWidth]);

    // Handle font-size change
    useEffect(() => {
        $('.reading-mode-body').css('zoom', fontSize)
    }, [fontSize]);

    // Handle font-family change
    useEffect(() => {
        if ('System' === fontFamily) {
            $('.reading-mode-body').css('font-family', 'system-ui');
            return;
        }

        if (!isMounted) {

            const id = `${fontFamily.replace(/ /g, '-')}-font`;

            if (!$(`#${id}`).length) {
                $(`<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=${fontFamily.replace(/ /g, '+')}" id="${id}">`).appendTo('head');
            }
        }

        $('.reading-mode-body').css('font-family', fontFamily);
    }, [fontFamily]);

    function handleAppearanceTooltip(e) {
        if (!$('.appearance-tooltip.show').length) return;

        if (!$(e.target).closest('.appearance-tooltip').length && !$(e.target).closest('.reading-mode-select__menu').length) {
            Tooltip.hide();
        }
    }

    return (
        <div className="reading-mode-tools">

            <div
                data-tooltip-content={wp.i18n.__('Exit Reading Mode', 'dracula-dark-mode')}
                data-tooltip-id={`exitReadingMode`}
                className={`reading-mode-tool`}
                onClick={handleClose}>
                <i className="dashicons dashicons dashicons-no"></i>

                <Tooltip id={`exitReadingMode`} place="right" variant="dark" effect="solid" />
            </div>

            {toolbar && toolbarTools.map(({ label, icon, key }) => {

                if (!tools.includes(key)) return;

                if (!dracula.isPro && ['speech', 'translate'].includes(key)) return;

                let isActive = false;
                if (key === 'fullScreen') {
                    isActive = isFullscreen;
                }
                if (key === 'toc') {
                    isActive = isTocOpen;
                }
                if (key === 'links') {
                    isActive = isLinksOpen;
                }

                if (key === 'scroll') {
                    isActive = isScrollActive;
                }

                if (key === 'appearance') {
                    isActive = isAppearanceActive;
                }

                return (
                    <>
                        <div key={key}
                            className={`reading-mode-tool ${isActive ? 'active' : ''}`}
                            onClick={(e) => {

                                if( 'appearance' === key ) {
                                    setIsAppearanceActive(!isAppearanceActive);
                                }

                                if( 'scroll' === key ) {
                                    setIsScrollActive(!isScrollActive);
                                }

                                if ('close' === key) {
                                    handleClose();
                                    return;
                                }

                                if ('fullScreen' === key) {
                                    handleFullScreen();
                                    return;
                                }

                                if ('toc' === key) {
                                    handleTOC();
                                    return;
                                }

                                if ('links' === key) {
                                    handleLinks();
                                    return;
                                }

                                if ('print' === key) {
                                    window.print();
                                    return;
                                }
                            }}

                        >
                            <i data-tooltip-id={key} className={icon}></i>
                            <Tooltip id={key} place="right" variant="dark" effect="solid" />
                        </div>

                        {'scroll' === key &&
                            <Tooltip
                                id={key}
                                isOpen={isScrollActive}
                                setIsOpen={setIsScrollActive}
                                variant="light"
                                effect="solid"
                                className="reading-mode-tooltip scroll-tooltip"
                                openOnClick="click"
                                clickable={true}
                                border={`1px solid #ddd`}
                                scrollHide={false}
                                afterShow={() => {
                                    setIsScrollActive(true);
                                }}
                                afterHide={() => {
                                    setIsScrollActive(false);
                                }}
                            >
                                <RadioGroup label="Scroll Speed"
                                    onChange={scrollSpeed => setScrollSpeed(scrollSpeed)}
                                    checked={scrollSpeed}>
                                    <Radio value="100">{wp.i18n.__('Slow', 'dracula-dark-mode')}</Radio>
                                    <Radio value="50">{wp.i18n.__('Medium', 'dracula-dark-mode')}</Radio>
                                    <Radio value="20">{wp.i18n.__('Fast', 'dracula-dark-mode')}</Radio>
                                </RadioGroup>
                            </Tooltip>
                        }

                        {'appearance' === key &&
                            <Tooltip
                                id={key}
                                isOpen={isAppearanceActive}
                                setIsOpen={setIsAppearanceActive}
                                variant="light"
                                effect="solid"
                                className="reading-mode-tooltip appearance-tooltip"
                                openOnClick={true}
                                clickable={true}
                                border={`1px solid #ddd`}
                                scrollHide={false}
                                afterShow={() => {
                                    setIsAppearanceActive(true);
                                    $(document).on('click', handleAppearanceTooltip);
                                }}
                                afterHide={() => {
                                    setIsAppearanceActive(false);

                                    $(document).off('click', handleAppearanceTooltip);
                                }}
                            >
                                <Appearance data={data} setData={setData} />
                            </Tooltip>
                        }

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