import React, { useState, useEffect } from "react";
import { getNonce, getDashboardData, isWooactive, cf7_status, formflow_status, isPro, getNoticeData } from '../../Helpers';
import axios from "axios";
import Tippy from '@tippy.js/react';
import CF7 from '../../../assets/icons/integration/contact-form-7.png'
import formdiable from '../../../assets/icons/integration/formdiable.png'
import gravity from '../../../assets/icons/integration/gravity.svg'
import WPForms from '../../../assets/icons/integration/WPForms.svg'
import formflow from '../../../assets/icons/integration/simpleform.png'
import moreForms from '../../../assets/icons/integration/more.png'
import WooCommerce from '../../../assets/icons/integration/woo.svg'
import { InstallingLoader } from '../../icons';
import NoticeModal from '../NoticeModal/NoticeModal';
import 'tippy.js/dist/tippy.css'
import './integration.scss'


const Integration = ({ onVisitTab }) => {

    const currentURL = window.location.href;
    const wpAdminIndex = currentURL.indexOf('/wp-admin/');
    const visitURL = currentURL.substring(0, wpAdminIndex);
    const adminURL = currentURL.substring(0, wpAdminIndex).replace(/(^\w+:|^)\/\//, '');

    const [iswooactive, setIswooactive] = useState(isWooactive());
    const [wooloading, setWOOLoading] = useState(false);

    const [isformflowactive, setIsformflowactive] = useState(formflow_status());
    const [formflowloading, setFormflowLoading] = useState(false);

    const [iscf7installed, setIsCFtInstalled] = useState(cf7_status());
    const [cf7loading, setCF7Loading] = useState(false);

    const [credentials, setCredentials] = useState([]);
    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_integration_settings_${siteIdentifier}`;

    // Save Functioanlity 

    useEffect(() => {
        getWebhook();
    }, []);

    function getWebhook() {
        const wpnts_integration_settings = getNoticeData().wpntswebhook_integration_settings || {
            cf7_webhook: '',
            formflow_webhook: '',
            cf7_active_notice: false,
            cf7_get_leads_with_notice: false,
            formflow_active_notice: false,
            formflow_get_leads_with_notice: false,
        };

        const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(wpnts_integration_settings));
        setCredentials(formData);
    }



    const [wpntswebhook_integration_settings, setWebhook] = useState({
        cf7_webhook: credentials.cf7_webhook,
        formflow_webhook: credentials.formflow_webhook,
        cf7_active_notice: credentials.cf7_active_notice,
        cf7_get_leads_with_notice: credentials.cf7_get_leads_with_notice,
        formflow_active_notice: credentials.formflow_active_notice,
        formflow_get_leads_with_notice: credentials.formflow_get_leads_with_notice
    });

    const handleFormDeckInstall = () => {
        const formDeckInstallURL = `${visitURL}/wp-admin/plugin-install.php?tab=plugin-information&plugin=simple-form&TB_iframe=true&width=772&height=851`;
        window.open(formDeckInstallURL, '_blank');
    };
    const handleWooInstall = () => {
        const formDeckInstallURL = `${visitURL}/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true&width=772&height=851`;
        window.open(formDeckInstallURL, '_blank');
    };

    const handleFormflowChange = e => {
        setWebhook(prev => ({ ...prev, formflow_webhook: e.target.value }))
    }
    const handleCF7Change = e => {
        setWebhook(prev => ({ ...prev, cf7_webhook: e.target.value }))
    }

    const handlecf7_active_notice = (e) => {
        const isChecked = event.target.checked;
        setWebhook((prev) => ({
            ...prev,
            cf7_active_notice: isChecked,
        }));
    }
    const handlecf7_get_leads_with_notice = (e) => {

        const isChecked = event.target.checked;
        setWebhook((prev) => ({
            ...prev,
            cf7_get_leads_with_notice: isChecked,
        }));
    }

    const handleformflow_active_notice = (e) => {
        const isChecked = event.target.checked;
        setWebhook((prev) => ({
            ...prev,
            formflow_active_notice: isChecked,
        }));
    }
    const handleformflow_get_leads_with_notice = (e) => {
        const isChecked = event.target.checked;
        setWebhook((prev) => ({
            ...prev,
            formflow_get_leads_with_notice: isChecked,
        }));
    }

    useEffect(() => {
        setWebhook({
            cf7_webhook: credentials.cf7_webhook,
            cf7_active_notice: credentials.cf7_active_notice,
            cf7_get_leads_with_notice: credentials.cf7_get_leads_with_notice,
            formflow_webhook: credentials.formflow_webhook,
            formflow_active_notice: credentials.formflow_active_notice,
            formflow_get_leads_with_notice: credentials.formflow_get_leads_with_notice

        });
    }, [credentials]);

    const handleSave = async e => {
        e.preventDefault()
        localStorage.setItem(localStorageKey, JSON.stringify(wpntswebhook_integration_settings));


        // Display "saving..." in the button
        const saveButton = e.target;
        saveButton.textContent = 'Saving...';


        /**
         * Add new plugin list name 
         * 
         */
        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_integration_settings`;
        try {
            const res = await axios.post(url, {
                wpntswebhook_integration_settings

            }, {
                headers: {
                    'content-type': 'application/json',
                    'X-WP-NONCE': appLocalizer.nonce
                }
            }).then(function (res) {

                // Reset the button text after saving is done
                saveButton.textContent = 'Save';

                if (res.data === 1) {
                    setModalConfig({
                        isOpen: true,
                        type: 'toast',
                        title: 'success!',
                        message: 'Integration configure successfully',
                        position: 'top-right'
                    });
                    setTimeout(closeModal, 3000);
                } else {
                    setModalConfig({
                        isOpen: true,
                        type: 'toast',
                        title: 'error!',
                        message: 'Integration configure failed',
                        position: 'top-right'
                    });

                    // Auto close the toast after 3 seconds
                    setTimeout(closeModal, 3000);
                }


            });

        } catch (err) {
            console.log(err);
        }


    }



    //Props to handle click from Integritions 
    const handleVisitTabs = (key) => {
        if (typeof onVisitTab === "function") {
            onVisitTab(key);
        }
    };

    const openFacebookInBrowser = () => {
        window.open('https://functiondeck.com/support/', '_blank');
    };

    /**
     * 
     * @param {WooCommerce} e 
     */
    const handleWoocommerceInstalled = async (e) => {
        e.preventDefault();
        setWOOLoading(true);
        if (iswooactive === 'notinstalled') {
            // If CF7 is not installed, install and activate it.
            installAndActivateWoocommerce();
        } else {
            // If CF7 is installed, just activate it.
            activateWoocommerce();
        }
    };

    const activateWoocommerce = () => {
        wp.ajax.send('activate_woocommerce_plugin', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                setWOOLoading(false); // Hide loader
                handleCheckisWoocommerceactiverecent();
            },
            error(error) {
                setWOOLoading(false); // Hide loader
                handleCheckisWoocommerceactiverecent();
            },
        });
    };

    const installAndActivateWoocommerce = () => {
        wp.ajax.send('install_and_activate_woocommerce_plugin', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                setWOOLoading(false); // Hide loader
                handleCheckisWoocommerceactiverecent();
            },
            error(error) {
                setWOOLoading(false); // Hide loader
                handleCheckisWoocommerceactiverecent();
            },
        });
    };


    //After install need to refetch the data to show on without page load
    const handleCheckisWoocommerceactiverecent = () => {
        wp.ajax.send('nts_is_woocommerce_installed', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                setIswooactive(response.status);
            },
            error(error) {
                console.error(error);
            },
        });

    };

    useEffect(() => {
        wp.ajax.send('nts_is_woocommerce_installed', {
            data: {
                nonce: getNonce(),
            },
            success(response) {

                setIswooactive(response.status);
            },
            error(error) {
                console.error(error);
            },
        });
    }, []);




    /**
     * 
     * @param {FormFlow} e 
     */
    const handleformflowInstalled = async (e) => {
        e.preventDefault();
        setFormflowLoading(true);
        if (isformflowactive === 'notinstalled') {
            // If CF7 is not installed, install and activate it.
            installAndActivateformflow();
        } else {
            // If CF7 is installed, just activate it.
            activateformflow();
        }
    };

    const activateformflow = () => {
        wp.ajax.send('activate_formflow_plugin', {
            data: {
                nonce: getNonce(),
            },
            success(response) {

                setFormflowLoading(false); // Hide loader
                handleCheckisformflowactiverecent();
            },
            error(error) {

                setFormflowLoading(false); // Hide loader
                handleCheckisformflowactiverecent();
            },
        });
    };

    const installAndActivateformflow = () => {
        wp.ajax.send('install_and_activate_formflow_plugin', {
            data: {
                nonce: getNonce(),
            },
            success(response) {

                setFormflowLoading(false); // Hide loader
                handleCheckisformflowactiverecent();
            },
            error(error) {

                setFormflowLoading(false); // Hide loader
                handleCheckisformflowactiverecent();
            },
        });
    };


    //After install need to refetch the data to show on without page load
    const handleCheckisformflowactiverecent = () => {
        wp.ajax.send('nts_is_formflow_installed', {
            data: {
                nonce: getNonce(),
            },
            success(response) {

                setIsformflowactive(response.status);
            },
            error(error) {
                console.error(error);
            },
        });

    };

    useEffect(() => {
        wp.ajax.send('nts_is_formflow_installed', {
            data: {
                nonce: getNonce(),
            },
            success(response) {

                setIsformflowactive(response.status);
            },
            error(error) {
                console.error(error);
            },
        });

    }, []);


    useEffect(() => {
        handleCheckisformflowactiverecent();
        const intervalId = setInterval(handleCheckisformflowactiverecent, 5000);
        return () => clearInterval(intervalId);
    }, []);


    /**
     * 
     * @param {Install and active contact form 7.} e 
     */

    const handleCF7Installed = async (e) => {
        e.preventDefault();
        setCF7Loading(true);
        if (iscf7installed === 'notinstalled') {
            // If CF7 is not installed, install and activate it.
            installAndActivateCF7();
        } else {
            // If CF7 is installed, just activate it.
            activateCF7();
        }
    };

    const activateCF7 = () => {
        wp.ajax.send('activate_cf7_plugin', {
            data: {
                nonce: getNonce(),
            },
            success(response) {

                setCF7Loading(false); // Hide loader
                handleCheckisCF7activerecent();
            },
            error(error) {

                setCF7Loading(false); // Hide loader
                handleCheckisCF7activerecent();
            },
        });
    };

    const installAndActivateCF7 = () => {
        wp.ajax.send('install_and_activate_cf7_plugin', {
            data: {
                nonce: getNonce(),
            },
            success(response) {

                setCF7Loading(false); // Hide loader
                handleCheckisCF7activerecent();
            },
            error(error) {

                setCF7Loading(false); // Hide loader
                handleCheckisCF7activerecent();
            },
        });
    };


    //After install need to refetch the data to show on without page load
    const handleCheckisCF7activerecent = () => {
        wp.ajax.send('nts_is_cf7_installed', {
            data: {
                nonce: getNonce(),
            },
            success(response) {

                setIsCFtInstalled(response.status);
            },
            error(error) {
                console.error(error);
            },
        });

    };

    useEffect(() => {
        wp.ajax.send('nts_is_cf7_installed', {
            data: {
                nonce: getNonce(),
            },
            success(response) {

                setIsCFtInstalled(response.status);
            },
            error(error) {
                console.error(error);
            },
        });
    }, []);


    return (
        <div className="nts-integration">
            <h3>Integration list </h3>
            <p>Choose the listed plugin and active to get notification from WP Notifier to Slack plugin</p>
            <div className='nts_integration_widget'>
                <div className="wcs_left">
                    <div className="form-integration-img">
                        <img className="integration-logo formflow-img" src={formflow} alt="formflow" />
                    </div>
                    <span className="formTitle">FormDeck: Simple Form Builder</span>

                    {(isformflowactive === 'inactive' || isformflowactive === 'notinstalled') && (
                        <div className="integration-inactive-overlay">
                            <div className="action-btns">
                                <div className="install-btn">
                                    <h3 className="inactive-text">Please {isformflowactive === 'inactive' ? 'Activate' : 'Install'} FormDeck</h3>
                                    <button
                                        className="formdeck-button"
                                        onClick={handleFormDeckInstall}
                                    >
                                        <span className="button-icon">
                                            <i className="fa fa-download"></i>
                                        </span>
                                        {isformflowactive === 'inactive' ? 'Activate Now' : 'Install Now'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}

                    {isformflowactive === 'active' && (
                        <div className="feature-inactive-overlay">
                            {/* Keep this if need to use form  */}
                            <div className="action-btns">
                                <div className="install-btn">
                                    <p className="inactive-text">Active FormFlow submission notification</p>
                                    <div className="integration-setting-save">
                                        <div className="fields">
                                            <label htmlFor="formflow-get-submission">Webhook</label>

                                            <input type="input" id="formflow-webhook" name="formflow-webhook" onChange={handleFormflowChange} value={wpntswebhook_integration_settings.formflow_webhook} />



                                        </div>
                                        <div className="fields">
                                            <input type="checkbox" id="formflow-active-notice" name="formflow-active-notice" onChange={handleformflow_active_notice} checked={wpntswebhook_integration_settings.formflow_active_notice} />
                                            <label htmlFor="formflow-active-notice">Check to active notification</label>
                                        </div>
                                        <div className="fields">
                                            <input type="checkbox" id="formflow-get-leads-with-notice" name="formflow-get-leads-with-notice" onChange={handleformflow_get_leads_with_notice} checked={wpntswebhook_integration_settings.formflow_get_leads_with_notice} />
                                            <label htmlFor="formflow-get-leads-with-notice">Check to send leads with notification</label>
                                        </div>
                                        <button className="install-action" onClick={handleSave}>Save</button>
                                    </div>

                                </div>
                            </div>

                        </div>
                    )}


                </div>

                <div className="wcs_left">
                    <div className="form-integration-img">
                        <img className="integration-logo WooCommerce-img" src={WooCommerce} alt="WooCommerce" />
                    </div>

                    {(iswooactive === 'inactive' || iswooactive === 'notinstalled') && (
                        <div className="integration-inactive-overlay">

                            <div className="action-btns">
                                <div className="install-btn">
                                    <h3 className="inactive-text">Please {iswooactive === 'inactive' ? 'Activate' : 'Install'} WooCommerce</h3>
                                    <button
                                        className="formdeck-button"
                                        onClick={handleWooInstall}
                                    >
                                        <span className="button-icon">
                                            <i className="fa fa-download"></i>
                                        </span>
                                        {iswooactive === 'inactive' ? 'Activate Now' : 'Install Now'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}
                    {iswooactive === 'active' && (
                        <div className="feature-inactive-overlay">
                            <div className="action-btns">
                                <div className="install-btn">
                                    <h3 className="inactive-text">Visit WooCommerce Tabs</h3>
                                    <div className="integration-setting-save">
                                        <button className="install-action" onClick={() => handleVisitTabs('woocommerce')}>Visit</button>

                                    </div>

                                </div>
                            </div>
                        </div>
                    )}

                </div>

                <div className="wcs_left">
                    <div className="form-integration-img">
                        <img className="integration-logo cf7-img" src={CF7} alt="cf7" />
                    </div>

                    {(iscf7installed === 'inactive' || iscf7installed === 'notinstalled') && (
                        <div className="integration-inactive-overlay">
                            <div className="action-btns">
                                <div className="install-btn">
                                    <h3 className="inactive-text">Please {iscf7installed === 'inactive' ? 'Activate' : 'Install'} CF7</h3>

                                </div>
                            </div>
                        </div>
                    )}

                    {iscf7installed === 'active' && (
                        <div className="feature-inactive-overlay">

                            <div className="action-btns">
                                <div className="install-btn">
                                    <p className="inactive-text">Active Contact Form 7 submission notification</p>
                                    <div className="integration-setting-save">
                                        <div className="fields">
                                            <label htmlFor="formflow-get-submission">Webhook</label>

                                            <input type="input" id="cf7-webhook" name="cf7-webhook" onChange={handleCF7Change} value={wpntswebhook_integration_settings.cf7_webhook} />


                                        </div>
                                        <div className="fields">
                                            <input type="checkbox" id="cf7-active-notice" name="cf7-get-notice" onChange={handlecf7_active_notice} checked={wpntswebhook_integration_settings.cf7_active_notice} />
                                            <label htmlFor="cf7-get-notice">Check to active notification</label>
                                        </div>
                                        <div className="fields">
                                            <input type="checkbox" id="cf7-get-leads-with-notice" name="cf7-get-leads-with-notice" onChange={handlecf7_get_leads_with_notice} checked={wpntswebhook_integration_settings.cf7_get_leads_with_notice} />
                                            <label htmlFor="cf7-get-leads-with-notice">Check to send leads with notification</label>
                                        </div>
                                        <button className="install-action" onClick={handleSave}>Save</button>
                                    </div>

                                </div>
                            </div>

                        </div>
                    )}

                </div>


            </div>

            <div className='nts_integration_widget_bottom'>

                <div className="wcs_left">
                    <div className="form-integration-img">
                        <img className="integration-logo wpforms-img" src={WPForms} alt="wpforms" />
                    </div>
                    {/* <span className="formTitle">WPForms</span> */}

                    <div className="integration-inactive-overlay">
                        <div className="action-btns">
                            <div className="install-btn">
                                <h3 className="inactive-text upcomming">Upcomming</h3>
                            </div>
                        </div>
                    </div>

                </div>


                <div className="wcs_left">
                    <div className="form-integration-img">
                        <img className="integration-logo gravity-img" src={gravity} alt="gravity" />
                    </div>
                    {/* <span className="formTitle">Grvity Forms</span> */}

                    <div className="integration-inactive-overlay">
                        <div className="action-btns">
                            <div className="install-btn">
                                <h3 className="inactive-text upcomming">Upcomming</h3>
                            </div>
                        </div>
                    </div>

                </div>
                <div className="wcs_left">
                    <div className="form-integration-img">
                        <img className="integration-logo formidable-img" src={formdiable} alt="formidable" />
                    </div>
                    {/* <span className="formTitle">Formidable</span> */}

                    <div className="integration-inactive-overlay">
                        <div className="action-btns">
                            <div className="install-btn">
                                <h3 className="inactive-text upcomming">Upcomming</h3>
                            </div>
                        </div>
                    </div>

                </div>
                <div className="wcs_left">
                    <div className="form-integration-img">
                        <img className="integration-logo more-forms-img" src={moreForms} alt="more-forms" />
                        <span className="formTitle"> More +</span>
                    </div>

                    <div className="integration-inactive-overlay">
                        <div className="action-btns">
                            <div className="install-btn">
                                <h3 className="inactive-text">Contact Us for feature request</h3>
                                <button className="install-action" onClick={openFacebookInBrowser}>Visit</button>
                            </div>
                        </div>
                    </div>

                </div>

            </div>

            <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 Integration