import React, { useState, useEffect } from "react";
import axios from "axios";
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
import ReactSwitchreview from 'react-switch'
import ReactSwitchsupport from 'react-switch'
import ReactPlayer from 'react-player'
import Modal from '../Modal/Modal';
import { isPro, getNoticeData } from '../../Helpers';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import orderStatus from '../../../assets/order-status.gif'
import Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import NoticeModal from '../NoticeModal/NoticeModal';
import "./theme.scss"

const Theme = ({ noticeSettings }) => {
    const [modalOpen, setModalOpen] = useState(false);
    const [passview, setPassview] = useState(false);
    const [credentials, setCredentials] = useState([]);
    const [getGlobalURL, setGetGlobalURL] = useState(false);

    // Extract the last part of the URL as the site identifier
    const pathParts = window.location.pathname.split("/").filter(Boolean);
    const indexOfAdmin = pathParts.indexOf('wp-admin');
    const siteIdentifier = indexOfAdmin !== -1 ? pathParts.slice(indexOfAdmin - 1, indexOfAdmin).pop() : pathParts.slice(-1).pop();
    // Use the site identifier to create a unique localStorage key
    const localStorageKey = `wpnts_theme_settings_${siteIdentifier}`;

    const proData = isPro();
    const allConditionsMet = proData;
    //END ------------------

    const handleViewpass = () => {
        passview === true ? setPassview(false) : setPassview(true)
    }
    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel'
    });
    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };

    useEffect(() => {
        getWebhook();
    }, []);

    function getWebhook() {
        const wpnts_theme_notify_settings = getNoticeData().wpntswebhook_theme_settings || {
            webhook: "",
            authorPaneltoMail: false,
            generalsettingspage: false,
            template_change_tracking: false,
            themeactivation: false,
            themedeletion: false,
            themeupdate: false,
            themeinstalled: false,
            theme_files_edited: false,

        };

        const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(wpnts_theme_notify_settings));
        setCredentials(formData);
    }


    const [wpntswebhook_theme_settings, setWebhook] = useState({
        webhook: credentials.webhook,
        themeupdate: credentials.themeupdate,
        themeinstalled: credentials.themeinstalled,
        theme_files_edited: credentials.theme_files_edited,
        themedeletion: credentials.themedeletion,
        themeactivation: credentials.themeactivation,
        generalsettingspage: credentials.generalsettingspage,
        template_change_tracking: credentials.template_change_tracking,
        authorPaneltoMail: credentials.authorPaneltoMail,

    });

    const handleGetGlobalURLChange = () => {
        // const globalSlack = getNoticeData().wpnts_global_api_settings.global_webhook ?? '';
        const globalSlack = noticeSettings.wpnts_global_api_settings.global_webhook ?? '';
        setWebhook(prev => ({ ...prev, webhook: globalSlack }))
    };

    const handleChange = e => {
        setWebhook(prev => ({ ...prev, [e.target.name]: e.target.value }))
    }

    /**
     * 
     * @param {Core WP CONFIG} e 
     * @returns 
     */
    const handleThemeactivation = e => {
        setWebhook(prev => ({ ...prev, themeactivation: e }));
    }

    /**
     * 
     * @param {HtAccess} e 
     * @returns 
     */
    const handleThemedeletion = e => {
        setWebhook(prev => ({ ...prev, themedeletion: e }));
    }

    const handleThemeupdate = e => {
        setWebhook(prev => ({ ...prev, themeupdate: e }));
    }

    const handleThemeinstalled = e => {
        setWebhook(prev => ({ ...prev, themeinstalled: e }));
    }

    const handleTheme_files_edited = e => {
        setWebhook(prev => ({ ...prev, theme_files_edited: e }));
    }

    const handleGeneralsettingspage = e => {
        setWebhook(prev => ({ ...prev, generalsettingspage: e }));
    }
    const handleTemplate_change_tracking = e => {
        if (!allConditionsMet) {
            setModalConfig({
                isOpen: true,
                type: 'premium',
                title: '🚀 Oops! This is a Premium Feature ',
                message: 'Evaluate the features and select a bundle based on your needs.',
                onConfirm: () => {
                    window.open('https://functiondeck.com/pricing/', '_blank');
                    closeModal();
                },
                confirmText: 'Upgrade Now',
                declineText: 'Maybe Later'
            });
            setWebhook((prev) => ({
                ...prev,
                template_change_tracking: false,
            }));
            return;
        }
        setWebhook(prev => ({ ...prev, template_change_tracking: e }));
    }

    const handleAuthorPaneltoMail = (e) => {
        const isChecked = event.target.checked;
        setWebhook((prev) => ({
            ...prev,
            authorPaneltoMail: isChecked,
        }));
    }


    useEffect(() => {
        setWebhook({
            webhook: credentials.webhook,
            themeupdate: credentials.themeupdate,
            themeinstalled: credentials.themeinstalled,
            theme_files_edited: credentials.theme_files_edited,
            themedeletion: credentials.themedeletion,
            themeactivation: credentials.themeactivation,
            generalsettingspage: credentials.generalsettingspage,
            template_change_tracking: credentials.template_change_tracking,
            authorPaneltoMail: credentials.authorPaneltoMail,
        });
    }, [credentials]);


    const handleSave = async e => {
        e.preventDefault()
        localStorage.setItem(localStorageKey, JSON.stringify(wpntswebhook_theme_settings));


        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_theme_settings`;
        try {
            const res = await axios.post(url, {
                wpntswebhook_theme_settings

            }, {
                headers: {
                    'content-type': 'application/json',
                    'X-WP-NONCE': appLocalizer.nonce
                }
            }).then(function (res) {
                // console.log(wpntswebhook_theme_settings)
            });

        } catch (err) {
            console.log(err);
        }


        setModalConfig({
            isOpen: true,
            type: 'toast',
            title: 'success',
            message: 'Webhook configure successfully',
            position: 'top-right'
        });
        setTimeout(closeModal, 3000);

    }

    return (
        <div className="acb_theme" id='acb_theme'>
            <div className="acb_left">
                <h3>Advance Theme settings panel
                    <a href="https://www.youtube.com/playlist?list=PL4m92NgWQaq5ttBH9gSYUX1r4c6rtgLg9" target="_blank"><PlayCircleIcon className='PlayCircleIcon' /></a>
                </h3>
                <br />

                <div className="wpnts-switch-sitescriptmodification">
                    {/* <p className="NEW_TAG_THEME">New</p> */}
                    <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-2" name="wpnts-switch-p-activation" id="themeactivation" onChange={handleThemeactivation} checked={wpntswebhook_theme_settings.themeactivation} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                        activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
                    <label htmlFor="themeactivation">Theme activation alert:</label>
                    <Tippy content="You will be notified once any theme activated on your site.">
                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                    </Tippy>
                </div>

                <div className="wpnts-switch-sitessecurityissues">
                    {/* <p className="NEW_TAG_THEME">New</p> */}
                    <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-3" name="wpnts-switch-p-deactivation" id="themedeletion" onChange={handleThemedeletion} checked={wpntswebhook_theme_settings.themedeletion} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                        activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
                    <label htmlFor="themedeletion">Theme deletion alert:</label>
                    <Tippy content="You will be notified once any theme deleted on your site..">
                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                    </Tippy>
                </div>

                <div className="wpnts-switch-sitessecurityissues">
                    {/* <p className="NEW_TAG_THEME">New</p> */}
                    <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-3" name="wpnts-switch-p-deactivation" id="themeinstalled" onChange={handleThemeinstalled} checked={wpntswebhook_theme_settings.themeinstalled} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                        activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
                    <label htmlFor="themeinstalled">Theme installed alert:</label>
                    <Tippy content="You will be notified once any theme installed on your site.">
                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                    </Tippy>
                </div>



                <div className="wpnts-switch-sitessecurityissues">
                    {/* <p className="NEW_TAG_THEME themes-tags">New</p> */}
                    <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-3" name="wpnts-switch-p-deactivation" id="themeupdate" onChange={handleThemeupdate} checked={wpntswebhook_theme_settings.themeupdate} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                        activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
                    <label htmlFor="themeupdate">Theme new update alert:</label>
                    <Tippy content="You will be notified once any Theme updated on your site.">
                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                    </Tippy>
                </div>

                <div className="wpnts-switch-sitessecurityissues">
                    {/* <p className="NEW_TAG_THEME">New</p> */}
                    <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-3" name="wpnts-switch-p-deactivation" id="generalsettingspage" onChange={handleGeneralsettingspage} checked={wpntswebhook_theme_settings.generalsettingspage} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                        activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
                    <label htmlFor="generalsettingspage">Settings General page modification alert:</label>
                    <Tippy content="You will be notified once any Settings => General page info updated on your site.">
                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                    </Tippy>
                </div>

                <div className="wpnts-switch-sitessecurityissues">
                    <p className="NEW_TAG_THEME">New</p>
                    <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-3" name="wpnts-switch-p-deactivation" id="theme_files_edited" onChange={handleTheme_files_edited} checked={wpntswebhook_theme_settings.theme_files_edited} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                        activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
                    <label htmlFor="theme_files_edited">Theme file edit alert:</label>
                    <Tippy content="You will be notified once any theme file edited on your site.">
                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                    </Tippy>
                </div>

                <div className="wpnts-switch-sitessecurityissues">
                    {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
                    <p className="NEW_TAG_THEME">New</p>
                    <div className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-3" name="wpnts-switch-p-deactivation" id="template_change_tracking" onChange={handleTemplate_change_tracking} checked={wpntswebhook_theme_settings.template_change_tracking} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                            activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
                        <label htmlFor="template_change_tracking">Page Template change notification:</label>
                        <Tippy content="You will be notified once any page template chanages">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>
                    </div>
                </div>

            </div>
            <div className="acb_right">
                {/* <form action="" id="wpntswebhook_theme_settings"> */}
                <form action="" id="wpnts_theme_notify_settings">
                    <div className="formInput">
                        <label htmlFor="webhook">Webhook URL</label>
                        <div className="wpnts-setting">
                            <div className="passimg" onClick={handleViewpass}>
                                {passview === false ? <VisibilityOffIcon className='passVisibility' /> : <VisibilityIcon className='passVisibility' />}
                            </div>
                            <input type={passview === true ? "text" : "password"} placeholder="add webhook " name="webhook" required onChange={handleChange} value={wpntswebhook_theme_settings.webhook} />
                        </div>
                    </div>

                    <div className="getGlobalURLCheckbox">
                        <input
                            type="checkbox"
                            id="getGlobalURL"
                            checked={getGlobalURL}
                            onChange={handleGetGlobalURLChange}
                        />
                        <label htmlFor="getGlobalURL">Click to get slack global webhook</label>
                    </div>

                    <button className="save-webhook" onClick={handleSave}>SAVE</button>
                </form>

            </div>

            {modalOpen && <><div class="wcs_popup_overlay"></div> <Modal setOpenModal={setModalOpen} /> </>}
            <NoticeModal
                isOpen={modalConfig.isOpen}
                onClose={closeModal}
                onConfirm={modalConfig.onConfirm}
                onDecline={closeModal}
                type={modalConfig.type}
                title={modalConfig.title}
                message={modalConfig.message}
                confirmText={modalConfig.confirmText}
                declineText={modalConfig.declineText}
                position={modalConfig.position || 'center'}
                autoClose={modalConfig.type === 'toast'}
                autoCloseTime={3000}
            />
        </div >
    )
}

export default Theme
