import React, { useState, useEffect } from "react";
import MonacoEditor from 'react-monaco-editor';
import axios from "axios";
import ReactSwitchsupport from 'react-switch'
import ReactPlayer from 'react-player'
import Modal from '../Modal/Modal';
import { isPro, debugMode, getNonce, maintenannoticeMode, getNoticeData } from '../../Helpers';
import orderStatus from '../../../assets/order-status.gif'
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
import Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import NoticeModal from '../NoticeModal/NoticeModal';
import './maintenance.scss'

const Maintenance = ({ noticeSettings }) => {

    const [modalOpen, setModalOpen] = useState(false);
    const [passview, setPassview] = useState(false);
    const [credentials, setCredentials] = useState([]);
    const [maintenancemodestatus, setMaintenancemode] = useState(maintenannoticeMode());


    // 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_maintenance_settings_${siteIdentifier}`;
    //END ------------------

    const proData = isPro();
    const allConditionsMet = proData;

    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel'
    });

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };
    const handleViewpass = () => {
        passview === true ? setPassview(false) : setPassview(true)
    }

    useEffect(() => {
        getWebhook();
    }, []);

    function getWebhook() {
        const wpntsmaintenannotice_log_settings = getNoticeData().wpnts_schedules_maintenannotice_settings || {
            webhook: '',
            maintenance_mode: false,
            show_maintenance_contact_form: false,
            maintenannotice: '',
        };

        const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(wpntsmaintenannotice_log_settings));
        setCredentials(formData);
    }


    // console.log(getNoticeData())

    const [wpntsmaintenannotice_log, setWebhook] = useState({
        webhook: credentials.webhook,
        maintenance_mode: credentials.maintenance_mode,
        show_maintenance_contact_form: credentials.show_maintenance_contact_form,
        maintenannotice: credentials.maintenannotice,

    });

    const handleChange = e => {
        setWebhook(prev => ({ ...prev, [e.target.name]: e.target.value }))
    }

    /**
     * 
     * @param {Core WP CONFIG} e 
     * @returns 
     */
    const handleMaintenancemode = e => {

        setWebhook(prev => ({ ...prev, maintenance_mode: e }));
    }

    const handleMaintenancenotification = 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'
            });

            return;
        }

        setWebhook(prev => ({ ...prev, maintenannotice: e }));
    }

    const handleMaintenanceform = e => {

        if (!allConditionsMet) {
            // setModalOpen(true)
            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'
            });

            return;
        }

        setWebhook(prev => ({ ...prev, show_maintenance_contact_form: e }));
    }



    useEffect(() => {
        setWebhook({
            webhook: credentials.webhook,
            maintenance_mode: credentials.maintenance_mode,
            show_maintenance_contact_form: credentials.show_maintenance_contact_form,
            maintenannotice: credentials.maintenannotice,
        });
    }, [credentials]);


    const handleSave = async e => {
        e.preventDefault()
        localStorage.setItem(localStorageKey, JSON.stringify(wpntsmaintenannotice_log));

        /**
         * Add new plugin list name 
         * 
         */
        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_wpntsmaintenannotice_log`;
        try {
            const res = await axios.post(url, {
                wpntsmaintenannotice_log

            }, {
                headers: {
                    'content-type': 'application/json',
                    'X-WP-NONCE': appLocalizer.nonce
                }
            }).then(function (res) {
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'success!',
                    message: 'Maintenannotice mode setting updated.',
                    position: 'top-right'
                });

                // Auto close the toast after 3 seconds
                setTimeout(closeModal, 3000);
            });

        } catch (err) {
            console.log(err);
        }


    }

    const MaintenannoticeModeStatus = () => {
        wp.ajax.send('maintenannotice_mode_status', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                setMaintenancemode(response.maintenance_status);
            },
            error(error) {
                console.error(error);
            },
        });

    };
    useEffect(() => {
        MaintenannoticeModeStatus();
        const intervalId = setInterval(MaintenannoticeModeStatus, 5000);
        return () => clearInterval(intervalId);
    }, []);

    return (
        <div className="acb_maintenance_mode" id='acb_maintenance_mode'>
            <div className="acb_left">
                <h3>Easy maintenance mode 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_TAGs">New</p> */}
                    <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-2" name="wpnts-switch-p-activation" id="maintenance_mode " onChange={handleMaintenancemode} checked={wpntsmaintenannotice_log.maintenance_mode} 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="maintenance_mode ">Active maintenance mode:</label>
                    <Tippy content="This can used to enable or disable the maintenance mode at one click.">
                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                    </Tippy>

                </div>


                <div className="wpnts-switch-sitescriptmodification">
                    {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
                    <div className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-2" name="wpnts-switch-p-activation" id="show_maintenance_contact_form" onChange={handleMaintenanceform} checked={wpntsmaintenannotice_log.show_maintenance_contact_form} 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="show_maintenance_contact_form">Active maintenance mode contact form:</label>
                        <Tippy content="A form will apear where user will submit there query.">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>

                    </div>

                </div>

                <div className="wpnts-switch-sitescriptmodification">
                    {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
                    <div className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-2" name="wpnts-switch-p-activation" id="maintenannotice" onChange={handleMaintenancenotification} checked={wpntsmaintenannotice_log.maintenannotice} 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="maintenannotice">Get maintenance mode form submit notification:</label>
                        <Tippy content="Every time when maintenannotice form submitted you will be informed">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>

                    </div>

                </div>

                <div className="wpnts-switch-sitessecurityissues">

                    <form action="" id="wpntsmaintenannotice_log_settings" >
                        {wpntsmaintenannotice_log.maintenannotice ?
                            <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={wpntsmaintenannotice_log.webhook} />
                                </div>
                            </div>
                            : ''}

                        <div className="error-log-btn">
                            <button className="save-webhook" onClick={handleSave}>Save</button>
                        </div>
                    </form>
                </div>

            </div>
            <div className="acb_right">
                <h3>
                    Maintenance mode : {' '}
                    <span className={`wpnts-log ${maintenancemodestatus['status'] === true ? 'active' : 'inactive'}`}>
                        {maintenancemodestatus['status'] === true ? 'active' : 'inactive'}
                    </span>
                </h3>

            </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 Maintenance
