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 Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import NoticeModal from '../NoticeModal/NoticeModal';
import "./comment.scss"

const Comment = ({ 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;

    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_comment_settings_${siteIdentifier}`;
    //END ------------------

    const handleViewpass = () => {
        passview === true ? setPassview(false) : setPassview(true)
    }

    useEffect(() => {
        getWebhook();
    }, []);

    function getWebhook() {
        const wpnts_comment_settings = getNoticeData().wpnts_schedules_interval_comment_settings || {
            commentmoderationnotifications: false,
            commentDisable: false,
            commentDisablefromAdmin: false,
            commentactionNotice: '',
            webhook: '',

        };

        const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(wpnts_comment_settings));
        setCredentials(formData);
    }


    const [wpntswebhook_comment_settings, setWebhook] = useState({
        webhook: credentials.webhook,
        commentactionNotice: credentials.commentactionNotice,
        commentmoderationnotifications: credentials.commentmoderationnotifications,
        commentDisable: credentials.commentDisable,
        commentDisablefromAdmin: credentials.commentDisablefromAdmin,
        authorPaneltoMail: credentials.authorPaneltoMail,

    });

    const handleGetGlobalURLChange = () => {
        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 }))
    }

    const handleAuthorPaneltoMail = (e) => {
        const isChecked = event.target.checked;
        setWebhook((prev) => ({
            ...prev,
            authorPaneltoMail: isChecked,
        }));
    }


    /**
     * 
     * @param {Core WP CONFIG} e 
     * @returns 
     */
    const handleCommentactionNotice = e => {
        setWebhook(prev => ({ ...prev, commentactionNotice: e }));
    }

    /**
     * 
     * @param {HtAccess} e 
     * @returns 
     */
    const handleCommentmoderationnotifications = e => {
        setWebhook(prev => ({ ...prev, commentmoderationnotifications: e }));
    }


    const handleCommentDisable = e => {
        setWebhook(prev => ({ ...prev, commentDisable: e }));
    }

    const handleCommentDisablefromAdmin = e => {
        setWebhook(prev => ({ ...prev, commentDisablefromAdmin: e }));
    }


    useEffect(() => {
        setWebhook({
            webhook: credentials.webhook,
            commentactionNotice: credentials.commentactionNotice,
            commentmoderationnotifications: credentials.commentmoderationnotifications,
            commentDisable: credentials.commentDisable,
            commentDisablefromAdmin: credentials.commentDisablefromAdmin,
            authorPaneltoMail: credentials.authorPaneltoMail,

        });
    }, [credentials]);


    const handleSave = async e => {
        e.preventDefault()
        localStorage.setItem(localStorageKey, JSON.stringify(wpntswebhook_comment_settings));

        //
        /**
         * Add new plugin list name 
         * 
         */
        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_comment_settings`;
        try {
            const res = await axios.post(url, {
                wpntswebhook_comment_settings

            }, {
                headers: {
                    'content-type': 'application/json',
                    'X-WP-NONCE': appLocalizer.nonce
                }
            }).then(function (res) {
                // console.log(wpntswebhook_comment_settings)
            });

        } catch (err) {
            console.log(err);
        }

        setModalConfig({
            isOpen: true,
            type: 'toast',
            title: 'Success',
            message: 'Webhook configure successfully',
            position: 'top-right'
        });

        // Auto close the toast after 3 seconds
        setTimeout(closeModal, 3000);

    }
    return (
        <div className="acb_comment" id='acb_comment'>
            <div className="acb_left">
                <h3>Advance Comment settings panel
                    <a href="https://www.youtube.com/playlist?list=PL4m92NgWQaq5ttBH9gSYUX1r4c6rtgLg9" target="_blank"><PlayCircleIcon className='PlayCircleIcon' /></a>
                </h3>
                <br />

                <div className="wpnts-switch-sitescriptmodification">
                    {/* {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''} */}
                    {/* <p className="NEW_TAG">New</p> */}
                    <div className={`media-feature`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-2" name="wpnts-switch-p-activation" id="commentactionNotice" onChange={handleCommentactionNotice} checked={wpntswebhook_comment_settings.commentactionNotice} 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="commentactionNotice">Site comment actions notification:</label>
                        <Tippy content="You will be notified whenever any post or product on your website is commented or replayed, including instant replays.">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>

                    </div>
                </div>

                <div className="wpnts-switch-sitessecurityissues">
                    {/* {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''} */}
                    {/* <p className="NEW_TAG">New</p> */}
                    <div className={`media-feature`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-3" name="wpnts-switch-p-deactivation" id="commentmoderationnotifications" onChange={handleCommentmoderationnotifications} checked={wpntswebhook_comment_settings.commentmoderationnotifications} 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="commentmoderationnotifications">Site comment received/moderation notifications:</label>
                        <Tippy content="You will be notified whenever any post or product on your website is commented or replayed, including instant replays.">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>

                    </div>
                </div>

                <div className="wpnts-switch-sitessecurityissues">
                    {/* {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''} */}
                    {/* <p className="NEW_TAG">New</p> */}
                    <div className={`media-feature`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-3" name="wpnts-switch-p-deactivation" id="commentDisable" onChange={handleCommentDisable} checked={wpntswebhook_comment_settings.commentDisable} 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="commentDisable">Disable comment form for visitors [frontend]:</label>
                        <Tippy content="This will disable comment for visitors. Only registerd user can comment.">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>

                    </div>
                </div>

                <div className="wpnts-switch-sitessecurityissues">
                    {/* {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''} */}
                    {/* <p className="NEW_TAG">New</p> */}
                    <div className={`media-feature`}>
                        <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-3" name="wpnts-switch-p-deactivation" id="commentDisablefromAdmin" onChange={handleCommentDisablefromAdmin} checked={wpntswebhook_comment_settings.commentDisablefromAdmin} 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="commentDisablefromAdmin">Disable comment thoughts:</label>
                        <Tippy content="This will hide all comments thoughts along with menu bar from admin.">
                            <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                        </Tippy>

                    </div>
                </div>


            </div>
            <div className="acb_right">

                {/* <form action="" id="wpntswebhook_comment_settings"> */}
                <form action="" id="wpnts_comment_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_comment_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>

                    {/* Mail  */}
                    <div className="formInput global-apis">
                        <label htmlFor="authorPaneltoMail">Notification send to Mail</label>
                        <div className="wpnts-setting global-settings-checkbox">
                            <input type="checkbox" id="authorPaneltoMail" name="authorPaneltoMail" onChange={handleAuthorPaneltoMail} checked={wpntswebhook_comment_settings.authorPaneltoMail} />
                            <label htmlFor="authorPaneltoMail">Check to receive notification to Mail</label>
                        </div>
                    </div>
                    {/* END  */}

                    <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 Comment
