import React, { useState, useEffect } from "react";
import MonacoEditor from 'react-monaco-editor';
import axios from "axios";
import ReactSwitchsupport from 'react-switch'
import Select from 'react-select';
import ReactPlayer from 'react-player'
import Modal from '../Modal/Modal';
import { isPro, debugMode, getNonce, getNoticeData, admin_list } 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 './downtimealerts.scss'

const Downtimealerts = ({ noticeSettings }) => {
    const [modalOpen, setModalOpen] = useState(false);
    const [passview, setPassview] = useState(false);
    const [credentials, setCredentials] = useState([]);
    const [getGlobalURL, setGetGlobalURL] = useState(false);
    const proData = isPro();
    const allConditionsMet = proData;


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

    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_emengency_shutdown_settings = getNoticeData().wpnts_schedules_interval_website_downtime_alerts || {
            webhook: "",
            fatal_errors: true,
            warning: true,
            parse_error: true,
            notice: true,
            error: true,
            user_error: true,
            user_warning: true,
            strict: true,
            deprecated: true,
            website_downtime_alerts: false,
            website_cron_create_notice: false,
            website_cron_delete_notice: false,

        };

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


    const [wpntswebhook_website_downtime_alerts, setWebhook] = useState({
        webhook: credentials.webhook,
        website_downtime_alerts: credentials.website_downtime_alerts,
        website_cron_create_notice: credentials.website_cron_create_notice,
        website_cron_delete_notice: credentials.website_cron_delete_notice,

        fatal_errors: credentials.fatal_errors,
        warning: credentials.warning,
        parse_error: credentials.parse_error,
        notice: credentials.notice,
        error: credentials.error,
        user_error: credentials.user_error,
        user_warning: credentials.user_warning,
        strict: credentials.strict,
        deprecated: credentials.deprecated,

    });

    const handleViewpass = () => {
        passview === true ? setPassview(false) : setPassview(true)
    }

    const handleEmengencyshutdownMode = e => {
        if (!allConditionsMet) {
            // setModalOpen(true)
            setModalConfig({
                isOpen: true,
                type: 'premium',
                title: '🚀 Oops! This is a Premium Feature',
                message: 'This is a premium feature. Upgrade now to access user kickout functionality!',
                onConfirm: () => {
                    window.open('https://functiondeck.com/pricing/', '_blank');
                    closeModal();
                },
                confirmText: 'Upgrade Now',
                declineText: 'Maybe Later'
            });
            return;
        }

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

    const handleCron_create_notice = e => {
        setWebhook(prev => ({ ...prev, website_cron_create_notice: e }));
    }
    const handleCron_delete_notice = e => {
        setWebhook(prev => ({ ...prev, website_cron_delete_notice: e }));
    }

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

    const handleGetGlobalURLChange = () => {
        const globalSlack = noticeSettings.wpnts_global_api_settings.global_webhook ?? '';
        setWebhook(prev => ({ ...prev, webhook: globalSlack }))
    };

    // single handle do all things for integration 
    const handleCheckmarkChange = (fieldName) => {

        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((prevSettings) => ({
            ...prevSettings,
            [fieldName]: !prevSettings[fieldName],
        }));
    };


    useEffect(() => {
        setWebhook({
            webhook: credentials.webhook,
            website_downtime_alerts: credentials.website_downtime_alerts,
            website_cron_create_notice: credentials.website_cron_create_notice,
            website_cron_delete_notice: credentials.website_cron_delete_notice,
            fatal_errors: credentials.fatal_errors,
            warning: credentials.warning,
            parse_error: credentials.parse_error,
            notice: credentials.notice,
            error: credentials.error,
            user_error: credentials.user_error,
            user_warning: credentials.user_warning,
            strict: credentials.strict,
            deprecated: credentials.deprecated,

        });
    }, [credentials]);


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


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

            }, {
                headers: {
                    'content-type': 'application/json',
                    'X-WP-NONCE': appLocalizer.nonce
                }
            }).then(function (res) {
            });

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

        setModalConfig({
            isOpen: true,
            type: 'toast',
            title: 'success',
            message: 'Settings updated',
            position: 'top-right'
        });
        setTimeout(closeModal, 3000);

    }


    return (
        <div className="acb_website_downtime_alerts" id='acb_website_downtime_alerts'>
            <div className="acb_left">
                <h3 className="esp-video">Website Cron & Downtime alerts
                    <a href="https://www.youtube.com/playlist?list=PL4m92NgWQaq5ttBH9gSYUX1r4c6rtgLg9" target="_blank"><PlayCircleIcon className='PlayCircleIcon' /></a>
                </h3>

                <br />
                <div className="wpnts-active-website_downtime_alerts">
                    <div className={`website_downtime_alerts_panel`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="emengency-supportSwitch-2" name="wpnts-switch-p-activation" id="website_cron_create_notice" onChange={handleCron_create_notice} checked={wpntswebhook_website_downtime_alerts.website_cron_create_notice} 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="website_cron_create_notice">Active cron event scheduling alert:</label>
                        <Tippy content="This advanced functionality allows admin to alert when a new cron active/created in site.">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>
                    </div>
                </div>


                <div className="wpnts-active-website_downtime_alerts">
                    <div className={`website_downtime_alerts_panel`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="emengency-supportSwitch-2" name="wpnts-switch-p-activation" id="website_cron_delete_notice" onChange={handleCron_delete_notice} checked={wpntswebhook_website_downtime_alerts.website_cron_delete_notice} 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="website_cron_delete_notice">Active scheduling cron delete alert:</label>
                        <Tippy content="This advanced functionality allows admin to alert when any scheduled cron delete from the site">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>
                    </div>
                </div>

                <div className="wpnts-active-website_downtime_alerts">
                    {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}

                    <div className={`website_downtime_alerts_panel wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="emengency-supportSwitch-2" name="wpnts-switch-p-activation" id="website_downtime_alerts" onChange={handleEmengencyshutdownMode} checked={wpntswebhook_website_downtime_alerts.website_downtime_alerts} 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="website_downtime_alerts">Active Website Downtime & Erros Alerts:</label>
                        <Tippy content="This advanced functionality allows admin to alert when his site becomes not accessible or encounters any errors.">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>
                    </div>

                </div>

                <div className={`start_emengency_shutdown wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>

                    {wpntswebhook_website_downtime_alerts.website_downtime_alerts ?
                        <div className="integrations">
                            <h3 className="integrations-title">Error Levels To Notify</h3>
                            <div className="integrations-settings">
                                {Object.keys(wpntswebhook_website_downtime_alerts).map((key) => (
                                    key !== 'webhook' && key !== 'website_downtime_alerts' &&
                                    <label key={key}>
                                        <input
                                            type="checkbox"
                                            name={key}
                                            checked={wpntswebhook_website_downtime_alerts[key]}
                                            onChange={() => handleCheckmarkChange(key)}
                                        />
                                        {key.replace('_', ' ').toUpperCase()}
                                    </label>
                                ))}
                            </div>
                        </div>
                        : ''}



                </div>

                <div className={`formInput ${wpntswebhook_website_downtime_alerts.globalSettings ? 'global-settings-mode' : 'inactive'}`}>
                    <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_website_downtime_alerts.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>

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

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