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 HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import { format } from 'date-fns';
import Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import { getNonce, getNoticeData } from '../../Helpers';
import NoticeModal from '../NoticeModal/NoticeModal';
import "./api.scss";

const Api = ({ noticeSettings }) => {
    const [passview, setPassview] = useState(false);
    const [credentials, setCredentials] = useState([]);
    const [testMessage, setTestMessage] = useState('');

    // 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_api_configration_${siteIdentifier}`;
    //END ------------------

    const handleViewpass = () => {
        passview === true ? setPassview(false) : setPassview(true)
    }

    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel'
    });

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };

    useEffect(() => {
        getWebhook();
    }, []);

    function getWebhook() {
        const wpnts_api_settings = getNoticeData().wpnts_global_api_settings || {
            global_webhook: "",
            global_interval: "",
            api_active: false,
            siteURL_add: false,
            mailconfig: false,
            activitylogduration: "30",
            logdurationtime: new Date().toISOString().split('T')[0]
        };

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



    const [wpnts_api_settings, setWebhook] = useState({
        global_webhook: credentials.global_webhook,
        global_interval: credentials.global_interval,
        api_active: credentials.api_active,
        siteURL_add: credentials.siteURL_add,
        mailconfig: credentials.mailconfig,
        recipiantmail: credentials.recipiantmail,
        activitylogduration: credentials.activitylogduration,
        logdurationtime: credentials.logdurationtime,

    });


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

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

    const handleApi_active = e => {
        setWebhook(prev => ({ ...prev, api_active: e }));
    }

    const handleSiteURL_add = e => {
        setWebhook(prev => ({ ...prev, siteURL_add: e }));
    }
    const handleMailconfig = e => {
        setWebhook(prev => ({ ...prev, mailconfig: e }));
    }

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


    useEffect(() => {
        setWebhook({
            global_webhook: credentials.global_webhook,
            global_interval: credentials.global_interval,
            api_active: credentials.api_active,
            siteURL_add: credentials.siteURL_add,
            mailconfig: credentials.mailconfig,
            recipiantmail: credentials.recipiantmail,
            activitylogduration: credentials.activitylogduration,
            logdurationtime: credentials.logdurationtime,
        });
    }, [credentials]);


    const handleGlobalinterval = (e) => {
        const selectedInterval = parseInt(e.target.value, 10);
        setWebhook((prev) => ({
            ...prev,
            global_interval: selectedInterval,
        }));
    }


    const handleSave = async e => {
        e.preventDefault()


        // Get the current date
        const currentDate = new Date();

        // Get activitylogduration from wpnts_api_settings and add it to the current date
        const durationDays = parseInt(wpnts_api_settings.activitylogduration, 10) || 1; // Default to 0 if not set

        // Add the number of days to the current date
        const futureDate = new Date(currentDate);
        futureDate.setDate(currentDate.getDate() + durationDays);

        // Format the future date as YYYY-MM-DD
        const formattedFutureDate = futureDate.toISOString().slice(0, 10);

        // Update the logdurationtime with the calculated future date
        setWebhook((prev) => ({
            ...prev,
            logdurationtime: formattedFutureDate
        }));

        // Prepare the updated wpnts_api_settings for submission
        const updatedSettings = {
            ...wpnts_api_settings,
            logdurationtime: formattedFutureDate // Add the future date to logdurationtime
        };

        // console.log(updatedSettings);

        // Save the settings to localStorage
        localStorage.setItem(localStorageKey, JSON.stringify(updatedSettings));


        // localStorage.setItem(localStorageKey, JSON.stringify(wpnts_api_settings));

        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_api_global_settings`;
        try {
            const res = await axios.post(url, {
                // wpnts_api_settings
                wpnts_api_settings: updatedSettings

            }, {
                headers: {
                    'content-type': 'application/json',
                    'X-WP-NONCE': appLocalizer.nonce
                }
            }).then(function (res) {
                // console.log(wpnts_api_settings)
            });

        } catch (err) {
            console.log(err);
        }

        setModalConfig({
            isOpen: true,
            type: 'toast',
            title: 'success!',
            message: 'Webhook configure successfully.',
            position: 'bottom-right'
        });
        setTimeout(closeModal, 3000);

    }

    const handleTestWebhook = async (e) => {
        e.preventDefault();

        const { global_webhook } = wpnts_api_settings;

        const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_sending_test`;

        try {
            const response = await axios.post(
                url,
                {
                    global_webhook, testMessage
                },
                {
                    headers: {
                        'content-type': 'application/json',
                        'X-WP-NONCE': appLocalizer.nonce,
                    },
                }
            );

            // console.log('Full response from the server:', response);

            if (response.data === 1) {

                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'success!',
                    message: 'Webhook test message send successfully.',
                    position: 'bottom-right'
                });
                setTimeout(closeModal, 3000);

                // Reset the testMessage
                setTestMessage('');
            } else {
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'error!',
                    message: 'Unexpected response from the server.',
                    position: 'bottom-right'
                });
                setTimeout(closeModal, 3000);
            }

        } catch (error) {
            console.error('Error sending data to server:', error.message);
        }

    };


    const handleResetlog = (event) => {
        event.stopPropagation();
        setModalConfig({
            isOpen: true,
            type: 'confirmation',
            title: 'Confirm Reset',
            message: 'Are you sure you want to reset the activity log from database?',
            onConfirm: () => {
                wp.ajax.send('wpnts_activity_data_resets', {
                    data: {
                        nonce: getNonce(),
                        confirm: true
                    },
                    success(response) {
                        if (response.status === 'success') {
                            setModalConfig({
                                isOpen: true,
                                type: 'toast',
                                title: 'success!',
                                message: 'Reset Successful.',
                                position: 'top-right'
                            });
                            setTimeout(closeModal, 3000);
                        } else if (response.status === 'failed') {
                            setModalConfig({
                                isOpen: true,
                                type: 'toast',
                                title: 'error!',
                                message: 'Reset Failed',
                                position: 'top-right'
                            });
                            setTimeout(closeModal, 3000);
                        } else if (response.status === 'errors') {
                            setModalConfig({
                                isOpen: true,
                                type: 'toast',
                                title: 'error!',
                                message: 'Reset Error.',
                                position: 'top-right'
                            });
                            setTimeout(closeModal, 3000);
                        }
                    },
                    error(error) {
                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'error!',
                            message: error.message || 'An unknown error occurred.',
                            position: 'top-right'
                        });
                        setTimeout(closeModal, 3000);
                    },
                });

                closeModal();
            },
            confirmText: 'Yes, Reset!',
            declineText: 'Cancel'
        });


    };


    return (
        <div className="acb_api" id='acb_api'>
            <div className="acb_left">
                <h3>Global slack webhook configuration
                </h3>
                <br />

                <div className="wpnts-switch-pluginactivation">
                    <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-2" name="wpnts-switch-p-activation" id="api_active" onChange={handleApi_active} checked={wpnts_api_settings.api_active} 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="api_active">Active global settings</label>
                    <Tippy content="This will be used in all other settings where webhook and time interval need.">
                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                    </Tippy>

                </div>

                <div className="wpnts-switch-pluginactivation">
                    {/* <div className="mail-config"> */}
                    <div className="parent-section">
                        <p className="BETA_TAG">Beta</p>
                        <div className="toogle-section">
                            <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-2" name="wpnts-switch-p-activation" id="mailconfig" onChange={handleMailconfig} checked={wpnts_api_settings.mailconfig} 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="mailconfig">Active Mail notification</label>
                            <Tippy content="Currently, this is a beta version that is used to receive plugin activation and deactivation notifications via email. Make sure to select 'Notification send to Mail' from the 'User activity' ➡️ 'Site settings panel'.">
                                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                            </Tippy>
                        </div>
                        <div className="section-child">
                            {wpnts_api_settings.mailconfig && (
                                <div className="formInput">
                                    <label className="form-feature-sub-heading" htmlFor="recipiantmail">Recepiant Mail</label>
                                    <div className="wpnts-setting">
                                        <input
                                            type="text"
                                            className="recipiantmail"
                                            id="recipiantmail"
                                            name="recipiantmail"
                                            value={wpnts_api_settings.recipiantmail}
                                            onChange={handleRecipiantmail}
                                        />


                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                <div className="wpnts-switch-pluginactivation">
                    <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-2" name="wpnts-switch-p-activation" id="siteURL_add" onChange={handleSiteURL_add} checked={wpnts_api_settings.siteURL_add} 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="siteURL_add">Include Site URL in Notices and Logs</label>
                    <Tippy content="Adds the site URL to notices and logs, helping the admin identify which site sent the log to Slack.">

                        <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                    </Tippy>

                </div>

                <div className="wpnts-switch-pluginactivation">
                    <div className="formInput activity-parents">
                        <label htmlFor="testMessage">Keep activity logs for (days)</label>
                        <div className="wpnts-setting">
                            <input
                                type="text"
                                placeholder="Maximum number of days"
                                name="activitylogduration"
                                value={wpnts_api_settings.activitylogduration}
                                onChange={handleActivityLog}
                            />
                        </div>
                        <p>
                            Expected reset date is- {` `}
                            {wpnts_api_settings.logdurationtime ? format(new Date(noticeSettings.wpnts_global_api_settings.logdurationtime ?? wpnts_api_settings.logdurationtime), 'MMMM d, yyyy') : '➡️ Hit SAVE to update'}
                        </p>

                        <p>Leave blank to reset activity log daily.</p>

                        <br />

                        <div className="delete-log">
                            <label htmlFor="reset-log">Reset Log Activities</label>
                            <button id="reset-log" onClick={(event) => handleResetlog(event)}>Reset</button>
                        </div>

                    </div>


                </div>


            </div>
            <div className="acb_right">
                <form action="" id="wpnts_api_settings">
                    <div className="formInput">
                        <label htmlFor="global_webhook">Webhook URL</label>
                        <div className="wpnts-setting global-settings">
                            <div className="passimg" onClick={handleViewpass}>
                                {passview === false ? <VisibilityOffIcon className='passVisibility' /> : <VisibilityIcon className='passVisibility' />}
                            </div>
                            <input type={passview === true ? "text" : "password"} placeholder="add webhook " name="global_webhook" required onChange={handleChange} value={wpnts_api_settings.global_webhook} />
                        </div>
                    </div>

                    <div className="formInput global_interval">
                        <label htmlFor="global_interval">Global Time Interval</label>
                        <div className="wpnts-setting">
                            <select
                                name="global_interval"
                                required
                                onChange={handleGlobalinterval}
                                value={wpnts_api_settings.global_interval}
                                className="site-select-fields"
                            >
                                <option value={60}>1 min interval</option>
                                <option value={180}>3 min</option>
                                <option value={300}>5 min</option>
                                <option value={1800}>30 min</option>
                                <option value={3600}>1 hour</option>
                                <option value={18000}>5 hours</option>
                                <option value={36000}>10 hours</option>
                                <option value={54000}>15 hours</option>
                                <option value={64800}>18 hours</option>
                                <option value={86400}>24 hours</option>
                                <option value={172800}>2 days</option>
                                <option value={259200}>3 days</option>
                                <option value={604800}>7 days</option>
                            </select>
                        </div>
                    </div>

                    <button className="save-webhook" onClick={handleSave}>SAVE</button>
                </form>
            </div>

            <div className="acb_video">
                <div className="formInput">
                    <label htmlFor="testMessage">Add your message</label>
                    <div className="wpnts-setting">
                        <input
                            type="text"
                            placeholder="Enter test message"
                            name="testMessage"
                            value={testMessage}
                            onChange={(e) => setTestMessage(e.target.value)}
                        />
                    </div>
                </div>
                <button className="save-webhook" onClick={handleTestWebhook}>
                    TEST WEBHOOK
                </button>
            </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 Api
