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, getNoticeData } from '../../Helpers';
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
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 Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import NoticeModal from '../NoticeModal/NoticeModal';
import './debugger.scss'

const Debugger = () => {
    const [modalOpen, setModalOpen] = useState(false);
    const [passview, setPassview] = useState(false);
    const [credentials, setCredentials] = useState([]);
    const [debugLog, setDebugLog] = useState(debugMode());
    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_error_settings_${siteIdentifier}`;
    //END ------------------


    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();
    }, []);

    // console.log(getNoticeData());

    function getWebhook() {
        const wpnts_site_debuglog_settings = getNoticeData().wpnts_schedules_interval_debuglog_settings || {
            webhook: "",
        };

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


    const [wpntswebhook_debug_log, setWebhook] = useState({
        webhook: credentials.webhook,
        wpdebuglog: credentials.wpdebuglog,
        wpdebuglognotice: credentials.wpdebuglognotice,
        globalSettings: credentials.globalSettings,

        authorPaneltoMail: credentials.authorPaneltoMail,

    });

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

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

    const handleUseGlobalSettings = (e) => {
        const isChecked = event.target.checked;
        setWebhook((prev) => ({
            ...prev,
            globalSettings: isChecked,
        }));
    }

    const handleAuthorPaneltoMail = (e) => {
        const isChecked = event.target.checked;
        setWebhook((prev) => ({
            ...prev,
            authorPaneltoMail: isChecked,
        }));
    }

    /**
     * 
     * @param {Core WP CONFIG} e 
     * @returns 
     */
    const handleDebuglog = e => {
        setWebhook(prev => ({ ...prev, wpdebuglog: e }));
    }

    const handleErrornotification = e => {
        setWebhook(prev => ({ ...prev, wpdebuglognotice: e }));
    }



    useEffect(() => {
        setWebhook({
            webhook: credentials.webhook,
            globalSettings: credentials.globalSettings,
            wpdebuglog: credentials.wpdebuglog,
            wpdebuglognotice: credentials.wpdebuglognotice,

            authorPaneltoMail: credentials.authorPaneltoMail,
        });
    }, [credentials]);


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

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

            }, {
                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: 'Debug mode updated',
            position: 'top-right'
        });
        setTimeout(closeModal, 3000);
    }

    /**
     * Clean debug log
     */
    const handleClean = async e => {
        e.preventDefault();

        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_wpntswebhook_debug_log_clean`;
        try {
            const cleanDebugLog = 1;
            const res = await axios.post(
                url,
                { cleanDebugLog: 1 },
                {
                    headers: {
                        'content-type': 'application/json',
                        'X-WP-NONCE': appLocalizer.nonce
                    }
                }
            );

            if (res.data === 1) {
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'success',
                    message: 'Debug log clean',
                    position: 'top-right'
                });
                setTimeout(closeModal, 3000);
            } else {
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'Error!',
                    message: 'Error in cleaning.',
                    position: 'top-right'
                });
                setTimeout(closeModal, 3000);
            }
        } catch (err) {
            console.log(err);
        }
    };


    const DebuglogResponse = () => {
        wp.ajax.send('wpnts_debug_mode_status', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                setDebugLog(response.debug_data);
            },
            error(error) {
                console.error(error);
            },
        });

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

    useEffect(() => {
        const localStorageKey = `wpnts_error_settings_${siteIdentifier}`;

        if ((debugLog['status'] === 'active' && !wpntswebhook_debug_log.wpdebuglog) ||
            (debugLog['status'] !== 'active' && wpntswebhook_debug_log.wpdebuglog)) {

            const updatedValue = debugLog['status'] === 'active';

            // Update the state
            setWebhook(prevState => ({
                ...prevState,
                wpdebuglog: updatedValue,
            }));

            // Update the value in local storage
            const currentSettings = JSON.parse(localStorage.getItem(localStorageKey)) || {};
            const updatedSettings = {
                ...currentSettings,
                wpdebuglog: updatedValue,
            };
            localStorage.setItem(localStorageKey, JSON.stringify(updatedSettings));
        }
    }, [debugLog['status'], siteIdentifier]);


    return (
        <div className="acb_debug_log" id='acb_debug_log'>
            <div className="acb_left">
                <h3>Advance Error Log panel

                    <a href="https://www.youtube.com/playlist?list=PL4m92NgWQaq5ttBH9gSYUX1r4c6rtgLg9" target="_blank"><PlayCircleIcon className='PlayCircleIcon' /></a>
                </h3>
                <br />
                <div className="wpnts-switch-sitescriptmodification">
                    <div className="wpnts_ispro">
                        <ReactSwitchsupport
                            uncheckedIcon={false}
                            checkedIcon={false}
                            className="sitessecurity-supportSwitch-2"
                            name="wpnts-switch-p-activation"
                            id="sitescriptmodification"
                            onChange={handleDebuglog}
                            checked={wpntswebhook_debug_log.wpdebuglog}
                            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="sitescriptmodification">Active debug mode in your website:</label>
                        <Tippy
                            content="Enable or disable debug mode. Note: Debug mode is not recommended for live sites. Use this in development environments only."
                        >
                            <span className="wcs-title">
                                <HelpOutlineIcon className="wcs_tooltip_icon" />
                            </span>
                        </Tippy>
                    </div>
                </div>


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

                    <div className={`wpnts_ispro`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-2" name="wpnts-switch-p-activation" id="wpdebuglognotice" onChange={handleErrornotification} checked={wpntswebhook_debug_log.wpdebuglognotice} 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="wpdebuglognotice">Get error notification:</label>
                        <Tippy content="Every time there is a new error on your site, you will be notified. It will only send errors once in order to prevent duplicates.">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>

                    </div>

                </div>

                <div className="wpnts-switch-sitessecurityissues">
                    <form action="" id="wpnts_site_debuglog_settings" className={`wpnts_ispro`}>

                        {wpntswebhook_debug_log.wpdebuglognotice ?
                            <div className="formInput global-apis">
                                <div className="wpnts-setting global-settings-checkbox">
                                    <input type="checkbox" id="useGlobalSettings" name="useGlobalSettings" onChange={handleUseGlobalSettings} checked={wpntswebhook_debug_log.globalSettings} />
                                    <label htmlFor="useGlobalSettings">Check to use global settings</label>
                                </div>
                            </div>
                            : ''}

                        {wpntswebhook_debug_log.wpdebuglognotice ?
                            <div className={`formInput ${wpntswebhook_debug_log.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_debug_log.webhook} />
                                </div>

                                <div className="getGlobalURLCheckbox">
                                    <input
                                        type="checkbox"
                                        id="getGlobalURL"
                                        checked={getGlobalURL}
                                        onChange={handleGetGlobalURLChange}
                                    />
                                    <label htmlFor="getGlobalURL">Click to get slack global webhook</label>
                                </div>


                                {/* Mail  */}
                                {/* <div className="formInput mail-config">
                                    <label htmlFor="authorPaneltoMail">Notification send to Mail</label>
                                    <br />
                                    <br />
                                    <div className="wpnts-setting global-settings-checkbox">
                                        <input type="checkbox" id="authorPaneltoMail" name="authorPaneltoMail" onChange={handleAuthorPaneltoMail} checked={wpntswebhook_debug_log.authorPaneltoMail} />
                                        <label htmlFor="authorPaneltoMail">Check to receive notification to Mail</label>
                                    </div>
                                </div> */}
                                {/* END  */}

                            </div>

                            : ''}



                        <div className="error-log-btn">
                            <button className="save-webhook" onClick={handleSave}>SAVE</button>
                            <button className="save-webhook clean" onClick={handleClean}>CLEAN LOG</button>
                        </div>
                    </form>
                </div>

            </div>
            <div className="acb_right">
                <h3>
                    Debug mode: {' '}
                    <span className={`wpnts-log ${debugLog['status'] === 'active' ? 'active' : 'inactive'}`}>
                        {debugLog['status'] === 'active' ? 'active' : 'inactive'}
                    </span>
                </h3>
                <h4>Make  sure to add below PHP constant to your <i>wp-config</i> file: <span><a target="_blank" href="https://wordpress.org/documentation/article/debugging-in-wordpress/">Guide</a></span></h4>
                <p>Maintin directory ( wp-content/debug.log ) within your site’s filesystem</p>

                <code> define('WP_DEBUG', true);</code>
                <code> define('WP_DEBUG_LOG', true);</code>
                <h4>Error log</h4>
                <div className="debug-log-files">
                    <MonacoEditor
                        width="100%"
                        height="400px"
                        // or 'javascript' or 'plaintext' depending on your content
                        language="javascript"
                        // or another theme of your choice 'vs-light & vs-dark'
                        theme="vs-light"
                        value={debugLog['log']}
                        options={{
                            readOnly: true,
                            renderSideBySide: false,
                            modules: false,
                            namedExport: false,
                            selectOnLineNumbers: false
                        }}
                    />
                </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 Debugger
