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 Modal from '../Modal/Modal';
import { isPro, debugMode, getNonce, getNoticeData, admin_list } from '../../Helpers';
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 ContentCopyIcon from '@mui/icons-material/ContentCopy';
import DeleteIcon from '@mui/icons-material/Delete';
import Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import NoticeModal from '../NoticeModal/NoticeModal';
import './emengency.scss'

const Emengency = () => {
    const [modalOpen, setModalOpen] = useState(false);
    const [credentials, setCredentials] = useState([]);
    const [debugLog, setDebugLog] = useState(debugMode());
    const proData = isPro();
    const allConditionsMet = proData;
    const adminList = admin_list();
    const options = JSON.parse(adminList);

    const [emergencyToken, setEmergencyToken] = useState('');
    const [tokenExpiry, setTokenExpiry] = useState('');
    const [showToken, setShowToken] = useState(false);
    const [activationLogs, setActivationLogs] = useState([]);

    const customFilterOption = (option, searchText) => {
        return option.label.toLowerCase().startsWith(searchText.toLowerCase());
    };

    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel'
    });

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: 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_Emengency_settings_${siteIdentifier}`;
    //END ------------------


    useEffect(() => {
        getWebhook();

        if (allConditionsMet) {
            fetchEmergencyToken();
            fetchActivationLogs();
        }
    }, []);


    // Get the webhook data from the localStorage - Priority of localstorage data so create new below function
    /* function getWebhook() {
        const wpnts_emengency_shutdown_settings = getNoticeData().wpnts_schedules_interval_debuglog_settings || {
            webhook: "",
        };

        const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(wpnts_emengency_shutdown_settings));
        setCredentials(formData);
    } */

    // Get the webhook data from the server and localStorage - Priority of server data
    function getWebhook() {
        // Get the server data from getNoticeData()
        const serverData = getNoticeData().wpntswebhook_emengency_shutdown || {
            webhook: "",
            start_emengency_shutdown: false,
            emengency_shutdown_mode: false,
            selected_super_admin: []
        };

        // Get the localStorage data
        const localData = JSON.parse(localStorage.getItem(localStorageKey) || '{}');

        // Combine them, prioritizing server data for critical fields
        const formData = {
            ...localData,
            start_emengency_shutdown: serverData.start_emengency_shutdown || localData.start_emengency_shutdown || false,
            emengency_shutdown_mode: serverData.emengency_shutdown_mode || localData.emengency_shutdown_mode || false,
            selected_super_admin: serverData.selected_super_admin || localData.selected_super_admin || []
        };

        // Update localStorage with the correct data
        localStorage.setItem(localStorageKey, JSON.stringify(formData));

        setCredentials(formData);
    }


    const [wpntswebhook_emengency_shutdown, setWebhook] = useState({
        start_emengency_shutdown: credentials.start_emengency_shutdown,
        emengency_shutdown_mode: credentials.emengency_shutdown_mode,
        selected_super_admin: credentials.selected_super_admin,

    });





    const handleEmengencyshutdownMode = 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, emengency_shutdown_mode: e }));
    }

    const handleSuperadmin = 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, selected_super_admin: e }));
    }

    const handleEmengencyShutdown = 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, start_emengency_shutdown: e }));

        // If emergency shutdown is being deactivated, refresh the token
        if (!e) {
            setTimeout(() => {
                fetchEmergencyToken();
            }, 1000);
        }
    }


    // Start Remote activation
    const fetchEmergencyToken = async () => {
        try {
            const response = await axios.get(
                `${appLocalizer.wpntsUrl}/wpnts/v1/get_emergency_token`,
                {
                    headers: {
                        'content-type': 'application/json',
                        'X-WP-NONCE': appLocalizer.nonce
                    }
                }
            );

            if (response.data && response.data.token) {
                setEmergencyToken(response.data.token);
                setTokenExpiry(response.data.expires_formatted);
            }
        } catch (error) {
            console.error('Error fetching emergency token:', error);
        }
    };

    const fetchActivationLogs = async () => {
        try {
            const response = await axios.get(
                `${appLocalizer.wpntsUrl}/wpnts/v1/emergency_activation_logs`,
                {
                    headers: {
                        'content-type': 'application/json',
                        'X-WP-NONCE': appLocalizer.nonce
                    }
                }
            );

            if (response.data && Array.isArray(response.data)) {
                setActivationLogs(response.data);
            }
        } catch (error) {
            console.error('Error fetching activation logs:', error);
        }
    };

    const clearActivationLogs = async () => {
        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;
        }
        try {
            const response = await axios.post(
                `${appLocalizer.wpntsUrl}/wpnts/v1/clear_emergency_logs`,
                {},
                {
                    headers: {
                        'content-type': 'application/json',
                        'X-WP-NONCE': appLocalizer.nonce
                    }
                }
            );

            if (response.data && response.data.success) {
                setActivationLogs([]);
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'Success!',
                    message: 'Activation logs cleared successfully',
                    position: 'top-right'
                });
                setTimeout(closeModal, 2000);
            }
        } catch (error) {
            console.error('Error clearing activation logs:', error);
            setModalConfig({
                isOpen: true,
                type: 'toast',
                title: 'Error!',
                message: 'Failed to clear logs',
                position: 'top-right'
            });
            setTimeout(closeModal, 2000);
        }
    };

    const copyTokenToClipboard = () => {
        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;
        }
        try {
            if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(emergencyToken)
                    .then(() => {
                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Copied!',
                            message: 'Token copied to clipboard',
                            position: 'top-right'
                        });
                        setTimeout(closeModal, 2000);
                    })
                    .catch(err => {
                        console.error('Clipboard write failed:', err);
                        fallbackCopyToClipboard(emergencyToken);
                    });
            } else {
                fallbackCopyToClipboard(emergencyToken);
            }
        } catch (error) {
            console.error('Copy to clipboard error:', error);
            fallbackCopyToClipboard(emergencyToken);
        }
    };

    const getRemoteActivationUrl = () => {
        const siteUrl = window.location.origin;
        return `${siteUrl}/wp-json/wpnts/v1/emergency_activate`;
    };

    const copyActivationAPI = () => {

        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;
        }

        const command = `${getRemoteActivationUrl()}?token=${emergencyToken}`;

        try {
            if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(command)
                    .then(() => {
                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Copied!',
                            message: 'Command copied to clipboard',
                            position: 'top-right'
                        });
                        setTimeout(closeModal, 2000);
                    })
                    .catch(err => {
                        console.error('Clipboard write failed:', err);
                        fallbackCopyToClipboard(command);
                    });
            } else {
                fallbackCopyToClipboard(command);
            }
        } catch (error) {
            console.error('Copy to clipboard error:', error);
            fallbackCopyToClipboard(command);
        }
    }

    const copyActivationCommand = () => {
        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;
        }

        const command = `curl -X POST "${getRemoteActivationUrl()}" -H "Content-Type: application/json" -d '{"token":"${emergencyToken}"}'`;

        try {
            if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(command)
                    .then(() => {
                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Copied!',
                            message: 'Command copied to clipboard',
                            position: 'top-right'
                        });
                        setTimeout(closeModal, 2000);
                    })
                    .catch(err => {
                        console.error('Clipboard write failed:', err);
                        fallbackCopyToClipboard(command);
                    });
            } else {
                fallbackCopyToClipboard(command);
            }
        } catch (error) {
            console.error('Copy to clipboard error:', error);
            fallbackCopyToClipboard(command);
        }
    };

    // Fallback method for copying to clipboard
    const fallbackCopyToClipboard = (text) => {
        try {
            // Create temporary input element
            const textArea = document.createElement('textarea');
            textArea.value = text;

            // Make the textarea out of viewport
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);

            // Select and copy
            textArea.focus();
            textArea.select();

            const successful = document.execCommand('copy');
            document.body.removeChild(textArea);

            if (successful) {
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'Copied!',
                    message: successful ? 'Text copied to clipboard' : 'Failed to copy',
                    position: 'top-right'
                });
                setTimeout(closeModal, 2000);
            } else {
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'Error',
                    message: 'Could not copy text',
                    position: 'top-right'
                });
                setTimeout(closeModal, 2000);
            }
        } catch (err) {
            console.error('Fallback copy failed:', err);
            setModalConfig({
                isOpen: true,
                type: 'toast',
                title: 'Error',
                message: 'Browser does not support copy to clipboard',
                position: 'top-right'
            });
            setTimeout(closeModal, 2000);
        }
    };

    // END 



    useEffect(() => {
        setWebhook({
            start_emengency_shutdown: credentials.start_emengency_shutdown,
            emengency_shutdown_mode: credentials.emengency_shutdown_mode,
            selected_super_admin: credentials.selected_super_admin,
        });
    }, [credentials]);


    const handleSave = async e => {
        e.preventDefault()

        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;
        }

        localStorage.setItem(localStorageKey, JSON.stringify(wpntswebhook_emengency_shutdown));

        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_wpntswebhook_emengency_shutdown`;
        try {
            const res = await axios.post(url, {
                wpntswebhook_emengency_shutdown
            }, {
                headers: {
                    'content-type': 'application/json',
                    'X-WP-NONCE': appLocalizer.nonce
                }
            });

            // If we just deactivated emergency mode, refresh the token
            if (wpntswebhook_emengency_shutdown.start_emengency_shutdown === false) {
                fetchEmergencyToken();
            }

            setModalConfig({
                isOpen: true,
                type: 'toast',
                title: 'Success!',
                message: 'Updated',
                position: 'top-right'
            });
            setTimeout(closeModal, 3000);

        } catch (err) {
            console.log(err);
            setModalConfig({
                isOpen: true,
                type: 'toast',
                title: 'Error!',
                message: 'Failed to update settings',
                position: 'top-right'
            });
            setTimeout(closeModal, 3000);
        }
    }



    return (
        <div className="acb_emengency_shutdown" id='acb_emengency_shutdown'>
            <div className="acb_left">
                <h3 className="esp-video">Emengency Shutdown panel
                    <a href="https://www.youtube.com/playlist?list=PL4m92NgWQaq5ttBH9gSYUX1r4c6rtgLg9" target="_blank"><PlayCircleIcon className='PlayCircleIcon' /></a>
                </h3>

                <br />

                <div className="wpnts-active-emengency-shutdown-mode settings-blocked-parents">
                    {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
                    <p className="NEW_TAGs">New</p>
                    <div className={`emengency_shutdown_mode_panel wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="emengency-supportSwitch-2" name="wpnts-switch-p-activation" id="emengency_shutdown_mode" onChange={handleEmengencyshutdownMode} checked={wpntswebhook_emengency_shutdown.emengency_shutdown_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="emengency_shutdown_mode">Emengency shutdown mode:</label>
                        <Tippy content="This advanced feature allows super admin to log out all users from the website at once. Once the 'Emergency Shutdown' is activated, everyone except super admins will be logged out instantly and won't be able to log back in until it's turned off.">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>
                    </div>

                    <div className="shutdownmode">
                        {wpntswebhook_emengency_shutdown.emengency_shutdown_mode ?
                            <div className="emergency-mode">
                                <div className={`formInput`}>
                                    <label htmlFor="users">Select Super Admin:</label>
                                    <Select
                                        id="users"
                                        options={options}
                                        isMulti
                                        value={wpntswebhook_emengency_shutdown.selected_super_admin}
                                        onChange={handleSuperadmin}
                                        filterOption={customFilterOption}
                                        placeholder="Search users..."
                                    />
                                </div>

                                <div className={`formInput start_emengency_shutdown wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
                                    <ReactSwitchsupport uncheckedIcon checkedIcon className="emengency-supportSwitch-2" name="wpnts-switch-p-activation" id="start_emengency_shutdown" onChange={handleEmengencyShutdown} checked={wpntswebhook_emengency_shutdown.start_emengency_shutdown} 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="start_emengency_shutdown">Start emengency shutdown manually: </label>
                                    <Tippy content="This will active the emengency shutdown.">
                                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                                    </Tippy>
                                </div>
                            </div>

                            : ''}



                        {/* {allConditionsMet && !wpntswebhook_emengency_shutdown.start_emengency_shutdown && ( */}
                        <div className={`remote-activation-section wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`} style={{ marginTop: '20px', padding: '15px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
                            <h4 style={{ marginTop: 0 }}>Remote Activation</h4>
                            <p style={{ fontSize: '14px' }}>Use this token to remotely activate emergency shutdown:</p>

                            <div className="token-container" style={{
                                display: 'flex',
                                alignItems: 'center',
                                backgroundColor: '#fff',
                                border: '1px solid #ddd',
                                borderRadius: '4px',
                                padding: '8px',
                                marginBottom: '10px'
                            }}>
                                <input
                                    type={showToken ? "text" : "password"}
                                    value={emergencyToken}
                                    readOnly
                                    style={{
                                        flex: 1,
                                        border: 'none',
                                        backgroundColor: 'transparent',
                                        fontSize: '14px'
                                    }}
                                />
                                <div style={{ display: 'flex', gap: '5px' }}>
                                    <button
                                        onClick={() => setShowToken(!showToken)}
                                        style={{
                                            background: 'none',
                                            border: 'none',
                                            cursor: 'pointer',
                                            color: '#555'
                                        }}
                                    >
                                        {showToken ? <VisibilityOffIcon /> : <VisibilityIcon />}
                                    </button>
                                    <button
                                        onClick={copyTokenToClipboard}
                                        style={{
                                            background: 'none',
                                            border: 'none',
                                            cursor: 'pointer',
                                            color: '#555'
                                        }}
                                    >
                                        <ContentCopyIcon />
                                    </button>
                                </div>
                            </div>

                            <p style={{ fontSize: '12px', color: '#666', marginBottom: '15px' }}>
                                Token expires: {tokenExpiry}
                            </p>

                            <div className="api-endpoint-info">
                                <p style={{ fontSize: '14px', marginBottom: '5px', display: 'flex', alignItems: 'center' }}>
                                    API Endpoint:
                                    <button
                                        onClick={copyActivationAPI}
                                        style={{
                                            background: 'none',
                                            border: 'none',
                                            cursor: 'pointer',
                                            marginLeft: '5px',
                                            color: '#555'
                                        }}
                                    >
                                        <ContentCopyIcon style={{ fontSize: '16px' }} />
                                    </button>

                                </p>
                                <code style={{
                                    display: 'block',
                                    backgroundColor: '#2b2b2b',
                                    color: '#e6e6e6',
                                    padding: '10px',
                                    borderRadius: '4px',
                                    overflowX: 'auto',
                                    fontSize: '13px',
                                    whiteSpace: 'pre-wrap',
                                    wordBreak: 'break-all'
                                }}>
                                    {`${getRemoteActivationUrl()}?token=${showToken ? emergencyToken : '••••••••••••••••••••••••••••••••'}`}
                                </code>
                            </div>


                            <div className="curl-command" style={{ marginTop: '10px' }}>
                                <p style={{ fontSize: '14px', marginBottom: '5px', display: 'flex', alignItems: 'center' }}>
                                    cURL Command:
                                    <button
                                        onClick={copyActivationCommand}
                                        style={{
                                            background: 'none',
                                            border: 'none',
                                            cursor: 'pointer',
                                            marginLeft: '5px',
                                            color: '#555'
                                        }}
                                    >
                                        <ContentCopyIcon style={{ fontSize: '16px' }} />
                                    </button>
                                </p>
                                <code style={{
                                    display: 'block',
                                    backgroundColor: '#2b2b2b',
                                    color: '#e6e6e6',
                                    padding: '10px',
                                    borderRadius: '4px',
                                    overflowX: 'auto',
                                    fontSize: '13px',
                                    whiteSpace: 'pre-wrap',
                                    wordBreak: 'break-all'
                                }}>
                                    {`curl -X POST "${getRemoteActivationUrl()}" -H "Content-Type: application/json" -d '{"token":"${showToken ? emergencyToken : '••••••••••••••••••••••••••••••••'}"}'`}
                                </code>
                            </div>


                            <p style={{ fontSize: '13px', color: '#666', marginTop: '10px' }}>
                                <strong>Note:</strong> This token will change after each activation. Keep it secure!
                            </p>
                        </div>
                        {/* // )} */}

                        {/* Complete the activation logs UI section */}
                        {allConditionsMet && activationLogs.length > 0 && (
                            <div className="activation-logs" style={{ marginTop: '20px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <h4 style={{ margin: 0 }}>Recent Activation Logs</h4>
                                    <button
                                        onClick={() => {
                                            setModalConfig({
                                                isOpen: true,
                                                type: 'confirmation',
                                                title: 'Clear Logs',
                                                message: 'Are you sure you want to clear all activation logs?',
                                                onConfirm: () => {
                                                    clearActivationLogs();
                                                    closeModal();
                                                },
                                                confirmText: 'Yes, Clear Logs',
                                                declineText: 'Cancel'
                                            });
                                        }}
                                        style={{
                                            background: 'none',
                                            border: 'none',
                                            cursor: 'pointer',
                                            color: '#dc3545',
                                            display: 'flex',
                                            alignItems: 'center',
                                            fontSize: '13px'
                                        }}
                                    >
                                        <DeleteIcon style={{ fontSize: '16px', marginRight: '4px' }} />
                                        Clear logs
                                    </button>
                                </div>
                                <ul style={{
                                    listStyle: 'none',
                                    padding: '10px',
                                    backgroundColor: '#f5f5f5',
                                    borderRadius: '4px',
                                    maxHeight: '200px',
                                    overflowY: 'auto',
                                    margin: '8px 0 0 0'
                                }}>
                                    {activationLogs.map((log, index) => (
                                        <li key={index} style={{
                                            padding: '8px',
                                            borderBottom: index < activationLogs.length - 1 ? '1px solid #ddd' : 'none',
                                            fontSize: '13px'
                                        }}>
                                            {log}
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        )}

                    </div>

                    {/* : ''} */}
                </div>

                <div className="start_emengency_shutdown">
                    <form action="" id="wpnts_emengency_shutdown_settings" className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>

                        <div className="error-log-btn">
                            <button className="save-webhook" onClick={handleSave}>SAVE</button>
                        </div>
                    </form>
                </div>

            </div>
            <div className="acb_right">
                <h3>
                    Emergency shutdown mode: {' '}
                    <span className={`wpnts-log ${wpntswebhook_emengency_shutdown.start_emengency_shutdown === true ? 'active' : 'inactive'}`}>
                        {wpntswebhook_emengency_shutdown.start_emengency_shutdown === true ? 'active' : 'inactive'}
                    </span>
                </h3>
                <p className="emer-info" style={{
                    fontSize: '14px',
                    lineHeight: '1.6',
                    color: '#444',
                    backgroundColor: '#f9f9f9',
                    padding: '12px',
                    borderLeft: '4px solid #ff5722',
                    borderRadius: '4px',
                    marginBottom: '15px'
                }}>
                    When the site is hacked, this tool can forcefully logout all hackers and allow <strong style={{ color: '#ff5722' }}>only super admin users</strong> to login. All other users will be forcefully logged out and automatically restricted from logging back in until emergency mode is turned off.
                </p>
                <h4>Make sure to add super admin before activating the <i>emergency shutdown:</i> <span><a target="_blank" href="https://functiondeck.com/docs/how-to-use-emengency-shutdown-panel/" style={{ color: '#0073aa', textDecoration: 'underline' }}>Guide</a></span></h4>
            </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 Emengency
