import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import ReactSwitchsupport from 'react-switch'
import KeyIcon from '@mui/icons-material/Key';
import Modal from '../Modal/Modal';
import { debugMode, getNonce, getNoticeData } from '../../Helpers';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
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 Turnstile, { useTurnstile } from "react-turnstile";
import './captcha.scss'

const Captcha = () => {
    const [activeTab, setActiveTab] = useState("integrations");
    const [loading, setLoading] = useState(false);
    const [verificationerror, setVerificationError] = useState(false);
    const [verificationText, setVerificationText] = useState('Connect');
    const [modalOpen, setModalOpen] = useState(false);
    const [passview, setPassview] = useState(false);
    const [passsecretview, setPasssecretview] = useState(false);
    const [credentials, setCredentials] = useState([]);
    const [debugLog, setDebugLog] = useState(debugMode());
    const [token, setToken] = useState('');

    const turnstile = useTurnstile();


    // 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_debugger_settings_${siteIdentifier}`;
    //END ------------------


    useEffect(() => {
        // Check the verification status in localStorage and set the button text accordingly
        const isVerified = localStorage.getItem('verified') === 'true';
        setVerificationText(isVerified ? "Connected" : "Connect");
    }, []);


    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel'
    });

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };

    const handleViewpasssitekey = () => {
        passview === true ? setPassview(false) : setPassview(true)
    }
    const handleViewpasssecretkey = () => {
        passsecretview === true ? setPasssecretview(false) : setPasssecretview(true)
    }

    useEffect(() => {
        getWebhook();
    }, []);


    function getWebhook() {
        const wpnts_site_captcha_settings = getNoticeData().wpnts_schedules_interval_debuglog_settings || {
            active_captcha: false,
            sitekeys: "",
            secretkey: "",
            submitBtnaccess: false,
            turnstiletheme: 'light',
            customMessage: '',

            wplogin: false,
            wpregister: false,
            wpresetpass: false,
            wpcomment: false,
            woomyaccountlogin: false,
            woolostresetpass: false,
        };

        const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(wpnts_site_captcha_settings));
        setCredentials(formData);
    }


    const [wpnts_captcha_settings, setWebhook] = useState({
        active_captcha: credentials.active_captcha,
        sitekeys: credentials.sitekeys,
        secretkey: credentials.secretkey,
        submitBtnaccess: credentials.submitBtnaccess,
        turnstiletheme: credentials.turnstiletheme,
        customMessage: credentials.customMessage,

        wplogin: credentials.wplogin,
        wpregister: credentials.wpregister,
        wpresetpass: credentials.wpresetpass,
        wpcomment: credentials.wpcomment,
        woomyaccountlogin: credentials.woomyaccountlogin,
        woolostresetpass: credentials.woolostresetpass,

    });

    const handleChange = e => {
        setWebhook(prev => ({ ...prev, [e.target.name]: e.target.value }))
    }

    const handleSubmitBtnaccess = (e) => {
        const isChecked = event.target.checked;
        setWebhook((prev) => ({
            ...prev,
            submitBtnaccess: isChecked,
        }));
    }

    const handleTurnstiletheme = (e) => {
        const selectedTheme = e.target.value;
        setWebhook((prev) => ({
            ...prev,
            turnstiletheme: selectedTheme,
        }));
    }


    const handleCaptchaactivation = (e) => {
        setWebhook(prev => ({ ...prev, active_captcha: e }));
    }

    // single handle do all things for integration 
    const handleCheckmarkChange = (fieldName) => {
        setWebhook((prevSettings) => ({
            ...prevSettings,
            [fieldName]: !prevSettings[fieldName],
        }));
    };

    // Generate token

    useEffect(() => {
        setWebhook({
            active_captcha: credentials.active_captcha,
            sitekeys: credentials.sitekeys,
            secretkey: credentials.secretkey,
            submitBtnaccess: credentials.submitBtnaccess,
            turnstiletheme: credentials.turnstiletheme,
            customMessage: credentials.customMessage,

            wplogin: credentials.wplogin,
            wpregister: credentials.wpregister,
            wpresetpass: credentials.wpresetpass,
            wpcomment: credentials.wpcomment,
            woomyaccountlogin: credentials.woomyaccountlogin,
            woolostresetpass: credentials.woolostresetpass,

        });
    }, [credentials]);


    const handleSave = async e => {
        e.preventDefault()

        // console.log(wpnts_captcha_settings);

        localStorage.setItem(localStorageKey, JSON.stringify(wpnts_captcha_settings));

        /**
         * Add new plugin list name 
         * 
         */
        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_wpnts_captcha_settings`;
        try {
            const res = await axios.post(url, {
                wpnts_captcha_settings

            }, {
                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: 'Turnstile settings updated',
            position: 'top-right'
        });

        // Auto close the toast after 3 seconds
        setTimeout(closeModal, 3000);

    }


    /**
     * Verify and connect
     */
    const handleConnect = async e => {
        e.preventDefault();
        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_wpnts_captcha_verify`;
        const connectButton = document.querySelector('button.save-webhook.clean');
        // Check if credentials.sitekeys and credentials.secretkey are empty
        const sitekeys = wpnts_captcha_settings.sitekeys;
        const secretkey = wpnts_captcha_settings.secretkey;
        try {
            setLoading(true);
            const res = await axios.post(
                url,
                {
                    sitekeys: sitekeys,
                    secretkey: secretkey,
                    token: token

                },
                {
                    headers: {
                        'content-type': 'application/json',
                        'X-WP-NONCE': appLocalizer.nonce
                    }
                }
            );

            connectButton.textContent = 'Processing';

            if (res.data.data.validated === true) {

                localStorage.setItem('verified', 'true');
                setVerificationText("Connected");
                setVerificationError(false);
                connectButton.textContent = 'Connected';
                setLoading(false);

                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'success',
                    message: 'Verification complete',
                    position: 'top-right'
                });
                setTimeout(closeModal, 3000);

            } else {

                connectButton.textContent = 'Failed';
                setVerificationText("failed");
                setVerificationError(true);
                localStorage.setItem('verified', 'false');
                setLoading(false);

                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'error!',
                    message: 'Error in Verification',
                    position: 'top-right'
                });
                setTimeout(closeModal, 3000);

            }
        } catch (err) {
            console.log(err);
            setLoading(false);
        } finally {
            setLoading(false);
            // Set the button text based on the verification status
            const isVerified = localStorage.getItem('verified') === 'true';
            setVerificationText(isVerified ? 'Connected' : 'Connect');
        }

    };

    // const isVerified = localStorage.getItem('verified');
    const handleTabClick = (tab) => {
        setActiveTab(tab);
    };


    return (
        <div className="acb_captcha" id='acb_captcha'>
            <div className="acb_left">
                <h3>Cloudflare turnstile for site security
                    <a href="https://www.youtube.com/playlist?list=PL4m92NgWQaq5ttBH9gSYUX1r4c6rtgLg9" target="_blank"><PlayCircleIcon className='PlayCircleIcon' /></a>
                </h3>

                <br />
                <div className="parent-section">
                    <div className="toogle-section">
                        <div className="wpnts-switch-sitescriptmodification">

                            {/* <p className="NEW_TAG cloud">New</p> */}
                            <div className={`wpnts_free`}>
                                <ReactSwitchsupport uncheckedIcon checkedIcon className="sitessecurity-supportSwitch-2" name="wpnts-switch-p-activation" id="active_captcha" onChange={handleCaptchaactivation} checked={wpnts_captcha_settings.active_captcha} 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="active_captcha">Enable Cloudflare Captcha:</label>
                                <Tippy content="Cloudflare's Turnstile feature enhances site security by enabling CAPTCHA on the login page, thereby bolstering overall protection for the website.">
                                    <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                                </Tippy>
                            </div>

                        </div>
                    </div>

                    <div className="wpnts-switch-sitessecurityissues">
                        <form action="" id="wpnts_site_captcha_settings" className={`wpnts_free`}>
                            {wpnts_captcha_settings.active_captcha ?
                                <div className="formInput global-apis">
                                    {/* <div className={`formInput ${wpnts_captcha_settings.submitBtnaccess ? 'global-settings-mode' : 'inactive'}`}> */}
                                    <div className={`formInput captchakeys`}>
                                        <label htmlFor="sitekeys">Add Site Key</label>
                                        <div className="wpnts-setting">
                                            <div className="passimg" onClick={handleViewpasssitekey}>
                                                {passview === false ? <VisibilityOffIcon className='passVisibility' /> : <VisibilityIcon className='passVisibility' />}
                                            </div>
                                            <input type={passview === true ? "text" : "password"} placeholder="add sitekeys " name="sitekeys" required onChange={handleChange} value={wpnts_captcha_settings.sitekeys} />
                                        </div>
                                    </div>

                                    <div className={`formInput captchakeys`}>
                                        <label htmlFor="secretkey">Add Secret Key</label>
                                        <div className="wpnts-setting">
                                            <div className="passimg" onClick={handleViewpasssecretkey}>
                                                {passsecretview === false ? <VisibilityOffIcon className='passVisibility' /> : <VisibilityIcon className='passVisibility' />}
                                            </div>
                                            <input type={passsecretview === true ? "text" : "password"} placeholder="add secretkey " name="secretkey" required onChange={handleChange} value={wpnts_captcha_settings.secretkey} />
                                        </div>

                                        {verificationerror && (
                                            <div className="ErrorMessage" style={{ border: '1px solid #ff6b6b', borderRadius: '5px', padding: '10px', marginBottom: '15px', marginTop: '15px' }}>
                                                <h5 style={{ color: '#ff6b6b' }}>Error! Your Secret Key is not matching with the Cloudflare Turnstile! <a href="https://dash.cloudflare.com/?to=/:account/turnstile" rel="noreferrer" target="_blank" style={{ color: '#020202', textDecoration: 'underline' }}>View</a></h5>
                                                <p style={{ color: '#ff6b6b' }}>
                                                    If you are sure that the site and secret keys are the same as in your Turnstile account but still not verified,
                                                    then first hit save to generate the new token and then press Connect. Still not works then reload the page to clean the cache.
                                                    Also, make sure to check the Turnstile widgets.
                                                </p>
                                            </div>
                                        )}

                                        <div className="verify-captcha-btn">
                                            {/* onClick={(e) => { handleConnect(e); handleSave(e); }} */}
                                            <button className="save-webhook clean" onClick={handleConnect} disabled={loading}>
                                                {loading ? 'Processing...' : verificationText}
                                            </button>

                                            <div className="save-settings">
                                                <button className="save-webhook" onClick={handleSave}>SAVE</button>
                                            </div>
                                        </div>

                                    </div>

                                    <hr />
                                    {/* Tab Headers */}
                                    <div className="tab-headers">
                                        <div
                                            className={`tab-header ${activeTab === "integrations" ? "active" : ""}`}
                                            onClick={() => handleTabClick("integrations")}
                                        >
                                            Integrations
                                        </div>

                                        <div
                                            className={`tab-header ${activeTab === "settings" ? "active" : ""}`}
                                            onClick={() => handleTabClick("settings")}
                                        >
                                            Additional settings
                                        </div>

                                    </div>
                                    <hr />

                                    <div className={`tab-content-section ${verificationText === "Connected" ? "widgets-active" : "widgets-inactive"}`}>
                                        {/* First Tab : integrations  */}
                                        <div className={`tab-content integrations-tab ${activeTab === "integrations" ? "active" : ""}`}>
                                            {/* Render your general integrations content here */}

                                            {activeTab === "integrations" && (
                                                <div className="integrations">
                                                    <h3 className="integrations-title">Set Captcha for WordPress/WooCommerce</h3>

                                                    <div className="integrations-settings">
                                                        <label>
                                                            <input
                                                                type="checkbox"
                                                                name="wplogin"
                                                                checked={wpnts_captcha_settings.wplogin}
                                                                onChange={() => handleCheckmarkChange('wplogin')}
                                                            />
                                                            WordPress Login
                                                        </label>
                                                        <label>
                                                            <input
                                                                type="checkbox"
                                                                name="wpregister"
                                                                checked={wpnts_captcha_settings.wpregister}
                                                                onChange={() => handleCheckmarkChange('wpregister')}
                                                            />
                                                            WodPress Register
                                                        </label>
                                                        <label>
                                                            <input
                                                                type="checkbox"
                                                                name="wpresetpass"
                                                                checked={wpnts_captcha_settings.wpresetpass}
                                                                onChange={() => handleCheckmarkChange('wpresetpass')}
                                                            />
                                                            WordPress Reset Password
                                                        </label>
                                                        <label>
                                                            <input
                                                                type="checkbox"
                                                                name="wpcomment"
                                                                checked={wpnts_captcha_settings.wpcomment}
                                                                onChange={() => handleCheckmarkChange('wpcomment')}
                                                            />
                                                            WordPress Comment
                                                        </label>
                                                        <label>
                                                            <input
                                                                type="checkbox"
                                                                name="woomyaccountlogin"
                                                                checked={wpnts_captcha_settings.woomyaccountlogin}
                                                                onChange={() => handleCheckmarkChange('woomyaccountlogin')}
                                                            />
                                                            WooCommerce Login/Register
                                                        </label>
                                                        <label>
                                                            <input
                                                                type="checkbox"
                                                                name="woolostresetpass"
                                                                checked={wpnts_captcha_settings.woolostresetpass}
                                                                onChange={() => handleCheckmarkChange('woolostresetpass')}
                                                            />
                                                            WooCommerce Lost/Reset Password
                                                        </label>

                                                    </div>
                                                </div>

                                            )}
                                        </div>

                                        {/* Second Tab : Settings  */}
                                        <div className={`tab-content settings-tab ${activeTab === "settings" ? "active" : ""}`}>
                                            {/* Render your general settings content here */}

                                            {activeTab === "settings" && (
                                                <div className="captcha-settings">
                                                    <h3 className="settings-title">Change Captcha settings</h3>
                                                    <div className={`submit-btn-access`}>
                                                        <input type="checkbox" id="submitBtnaccess" name="submitBtnaccess" onChange={handleSubmitBtnaccess} checked={wpnts_captcha_settings.submitBtnaccess} />
                                                        <label htmlFor="submitBtnaccess">Submit button access</label>
                                                        <p>Check to disable the submit button until the Turnstile check is completed</p>
                                                    </div>

                                                    <div className={`formInput widgets-theme-select`}>
                                                        <label htmlFor="interval_plugin_update">Select Turnstile Widgets Theme</label>
                                                        <div className="wpnts-setting">
                                                            <select
                                                                name="interval_plugin_update"
                                                                required
                                                                onChange={handleTurnstiletheme}
                                                                value={wpnts_captcha_settings.turnstiletheme}
                                                                className="site-select-fields"
                                                            >
                                                                <option value='light'>Light</option>
                                                                <option value='dark'>Dark</option>
                                                                <option value='auto'>Auto</option>

                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>

                                            )}

                                            {wpnts_captcha_settings.active_captcha ?
                                                <div className={`formInput `}>
                                                    <label htmlFor="customMessage">Custom message</label>
                                                    <div className="wpnts-setting">
                                                        <input type="text" placeholder="System that you are a human" name="customMessage" required onChange={handleChange} value={wpnts_captcha_settings.customMessage} />
                                                    </div>
                                                    <p>Leaving it blank will show the default “System you are human” message</p>

                                                </div>

                                                : ''}
                                        </div>
                                    </div>



                                </div>
                                : ''}

                            {!wpnts_captcha_settings.active_captcha ?
                                <div className="save-settings">
                                    <button className="save-webhook" onClick={handleSave}>SAVE</button>
                                </div>
                                : ''}


                        </form>
                    </div>

                </div>
            </div>
            <div className="acb_right">
                <div className="turnstile-widgets">
                    <Turnstile
                        sitekey={wpnts_captcha_settings.sitekeys}
                        theme={wpnts_captcha_settings.turnstiletheme}
                        onVerify={(token) => {
                            // console.log(token);
                            setToken(token);
                        }}
                    />
                </div>

                <div className="cloudflare-get-key"><KeyIcon className="key-icon" />
                    <span><a target="_blank" href="https://dash.cloudflare.com/?to=/:account/turnstile" rel="noreferrer" className="get-keys">Click here</a> to get your <strong>Site Key</strong> and <strong>Secret Key</strong> then paste them below</span>
                </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 Captcha
