import ReactSelect from "react-select";
import {Tooltip} from "react-tooltip";
import {animation, Item, Menu, Submenu, useContextMenu} from "react-contexify";
import AppContext from "../../contexts/AppContext";
import {copyShortcode, removeIdParam, showProModal} from "../../includes/functions";

const {useContext} = React;
const {
    Spinner, Button, ButtonGroup,
} = wp.components;

const MENU_ID = "embed-context-menu";

export default function Header() {
    const isPro = radioPlayer.isPro;

    const context = useContext(AppContext);

    const {
        players,
        edit,
        setEdit,
        editData,
        setEditData,
        updating,
        updatePlayer,
        isDirty,
    } = context;

    const {show} = useContextMenu({id: MENU_ID});

    const selectPage = async () => {
        try {
            const pages = await wp.ajax.post('rp_get_pages', {nonce: radioPlayer.nonce});

            const options = pages.map((page) => ({
                value: page.id,
                label: page.title,
            }));

            let selectedPageId = null;

            Swal.fire({
                title: wp.i18n.__("Select a Page", "radio-player"),
                html: `
                        <p>${wp.i18n.__("Select a page to embed the shortcode.", "radio-player")}</p>
                        <div id="react-select-container"></div>
                      `,
                didOpen: () => {
                    const container = document.getElementById('react-select-container');

                    if (container) {
                        const root = wp.element.createRoot(container);
                        root.render(
                            wp.element.createElement(ReactSelect, {
                                options,
                                onChange: (selected) => {
                                    selectedPageId = selected?.value;
                                },
                                placeholder: wp.i18n.__('Search and select a page...', 'radio-player'),
                                isSearchable: true,
                                menuPortalTarget: document.body,
                                className: 'radio-player-select',
                                styles: {
                                    container: (base) => ({
                                        ...base,
                                        width: '100%',
                                        zIndex: 10000,
                                    }),
                                    menuPortal: (base) => ({
                                        ...base,
                                        zIndex: 999999,
                                    }),
                                },
                            })
                        );
                    }
                },
                preConfirm: () => {
                    if (!selectedPageId) {
                        Swal.showValidationMessage(wp.i18n.__("Please select a page.", "radio-player"));
                        return false;
                    }

                    window.location.href = `${radioPlayer.admin_url}/post.php?post=${selectedPageId}&action=edit`;
                },
                confirmButtonText: wp.i18n.__("Let's Go", "radio-player"),
                showCloseButton: true,
                customClass: {
                    container: "radio-player-swal no-icon",
                },
            });
        } catch (err) {
            Swal.showValidationMessage(wp.i18n.__("Please select a page.", "radio-player"));
        }
    }

    const createPage = () => {
        Swal.fire({
            title: wp.i18n.__("Create New Page", "radio-player"),
            text: wp.i18n.__("Enter the title for the new page.", "radio-player"),
            input: 'text',
            inputPlaceholder: wp.i18n.__("Enter page title", "radio-player"),
            confirmButtonText: wp.i18n.__("Let's Go", "radio-player"),
            showCloseButton: true,
            customClass: {
                container: "radio-player-swal no-icon",
            },
            preConfirm: (title) => {

                const data = {
                    title,
                    id: editData.id,
                    nonce: radioPlayer.nonce,
                };

                return wp.ajax.post('rp_create_page', data).then((response) => {
                    window.location.href = `${radioPlayer.admin_url}/post.php?post=${response.id}&action=edit`;
                }).catch((err) => {
                    console.log(err);
                    Swal.showValidationMessage(wp.i18n.__("Failed to create page.", "radio-player"));
                });


            }
        });
    }

    const handleEmbedCode = () => {

        if (!isPro) {
            showProModal(wp.i18n.__('Upgrade to PRO to embed the player on any website or page.', 'radio-player'));
            return;
        }

        Swal.fire({
            title: wp.i18n.__('Embed Code', 'radio-player'),
            html: `<p class="embed-code-title">${wp.i18n.__('Insert the following code into any webpage to showcase the player.', 'radio-player')}</p><textarea class="embed-code" rows="5" readonly>${`<iframe src="${radioPlayer.site_url}/?radio_player=${editData.id}&embed" width="100%" height="350" frameborder="0"></iframe>`}</textarea>`,
            showCloseButton: true,
            showCancelButton: false,
            confirmButtonText: wp.i18n.__('Copy', 'radio-player'),
            confirmButtonColor: '#40CE87',
            customClass: {
                container: 'radio-player-swal embed-code-swal no-icon',
            },
            didOpen: () => {
                document.querySelector('.embed-code').select();

            }
        }).then((result) => {
            if (result.value) {
                document.querySelector('.embed-code').select();
                document.execCommand("copy");

                Swal.fire({
                    title: wp.i18n.__('Copied!', 'radio-player'),
                    text: wp.i18n.__('Embed code copied to clipboard', 'radio-player'),
                    icon: 'success',
                    toast: true,
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true,
                });
            }
        });
    }

    return (
        <div className="radio-player-app__header">

            <div className="header-title">

                {/* Back */}
                {!!edit &&
                    <button
                        type={`button`}
                        className="radio-player-btn btn-back"
                        onClick={() => {
                            removeIdParam();
                            setEdit(null);
                        }}>
                        <i className="dashicons dashicons-arrow-left-alt2"></i>
                        <span>{wp.i18n.__("Back", "radio-player")}</span>

                        <Tooltip
                            anchorSelect={`.btn-back`}
                            place="right"
                            content={wp.i18n.__("Back to players list", "radio-player")}
                            delayShow={500}
                        />

                    </button>

                }

                <img src={`${radioPlayer.plugin_url}/assets/images/radio-player-logo.png`}/>

                {!edit ?
                    <span>{wp.i18n.__("Radio Player", "radio-player")}</span>
                    :
                    <>
                        <label
                            htmlFor={"player-title"}>{editData.id > 0 ? wp.i18n.__("Edit Player", "radio-player") : wp.i18n.__("Add New Player", "radio-player")}</label>
                        <input type="text"
                               onChange={e => setEditData({...editData, title: e.target.value})}
                               value={editData.title}
                               placeholder={wp.i18n.__(`Enter Player Title`, "radio-player")}
                               id={"player-title"}
                        />
                    </>
                }

            </div>

            <div className="header__actions">

                {!!edit ?
                    <>
                        {/*----- Usage -----*/}
                        {
                            editData.id > 0 && (
                                <>
                                    <ButtonGroup
                                        className="radio-player-btn-group"
                                        aria-label={wp.i18n.__("Shortcode Actions", "radio-player")}
                                    >
                                        <Button
                                            variant="primary"
                                            onClick={() => {
                                                window.open(`${radioPlayer.site_url}/radio-player/${editData.id}`, `radio-player-${editData.id}`);
                                            }}
                                        >
                                            <i className="dashicons dashicons-visibility"></i>
                                            {wp.i18n.__("View", "radio-player")}
                                        </Button>
                                        <Button
                                            variant="primary"
                                            onClick={(e) => show(e)}
                                        >
                                            <i className="dashicons dashicons-embed-post"></i>
                                            {wp.i18n.__("Embed", "radio-player")}
                                        </Button>
                                    </ButtonGroup>

                                    {/*--- Embed Context Menu ---*/}
                                    <Menu
                                        id={MENU_ID}
                                        animation={animation.fade}
                                        className={"radio-player-context-menu embed-context-menu"}
                                    >
                                        <Item
                                            onClick={() => copyShortcode(editData.id)}
                                            className={`context-menu-item`}
                                        >
                                            <i className="dashicons dashicons-shortcode"></i>
                                            {wp.i18n.__("Copy Shortcode", "radio-player")}
                                        </Item>

                                        <Item
                                            onClick={handleEmbedCode}
                                            className={`context-menu-item`}
                                        >
                                            <i className="dashicons dashicons-editor-code"></i>
                                            {wp.i18n.__("Embed Code", "radio-player")}
                                        </Item>

                                        <Item className={`context-menu-item`}>
                                            <Submenu
                                                label={
                                                    <>
                                                        <i className="dashicons dashicons-welcome-add-page"></i>
                                                        {wp.i18n.__("Embed in Page", "radio-player")}
                                                    </>
                                                }
                                                className="context-submenu"
                                                arrow={<i className={`dashicons dashicons-arrow-right`}></i>}
                                            >

                                                <Item
                                                    onClick={selectPage}
                                                    className="context-menu-item"
                                                >
                                                    <i className="dashicons dashicons-edit-page"></i>
                                                    {wp.i18n.__("Select Existing Page", "radio-player")}
                                                </Item>


                                                <Item
                                                    onClick={createPage}
                                                    className="context-menu-item"
                                                >
                                                    <i className="dashicons dashicons-plus-alt2"></i>
                                                    {wp.i18n.__("Create New Page", "radio-player")}
                                                </Item>


                                            </Submenu>
                                        </Item>
                                    </Menu>
                                </>
                            )
                        }

                        {/*--- Save ---*/}
                        <button type={'button'} className={`radio-player-btn btn-save ${isDirty ? '' : 'disabled'}`}
                                onClick={() => updatePlayer(editData)}>
                            {updating ? <Spinner/> : <i className={`dashicons dashicons-saved`}></i>}
                            <span>{isDirty ? wp.i18n.__("Save", "radio-player") : wp.i18n.__("Saved", "radio-player")}</span>
                        </button>

                    </>
                    :
                    <button
                        data-tooltip-id={`add-new-pro`}
                        type={'button'}
                        className={`radio-player-btn`}
                        onClick={() => {

                            if (!isPro && players.length >= 10) {
                                showProModal(wp.i18n.__("You can't add more than 10 players in the free version.", "radio-player"));
                                return;
                            }

                            setEdit(-1);
                        }}
                    >
                        <i className={`dashicons dashicons-plus`}></i>
                        <span>{wp.i18n.__('Add New Player', 'radio-player')}</span>
                    </button>

                }

            </div>

        </div>
    )
}