import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import ExtensionIcon from '@mui/icons-material/Extension';
import CircularProgress from '@mui/material/CircularProgress';
import BookmarkAddedIcon from '@mui/icons-material/BookmarkAdded';
import SupportAgentIcon from '@mui/icons-material/SupportAgent';
import Person3Icon from '@mui/icons-material/Person3';
import ConfirmationNumberIcon from '@mui/icons-material/ConfirmationNumber';
import SettingsInputHdmiIcon from '@mui/icons-material/SettingsInputHdmi';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import FullscreenIcon from '@mui/icons-material/Fullscreen';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import './widgets.scss'
import React, { useState, useEffect } from "react";
import { getNonce, getDashboardData } from '../../Helpers';


const WCSWidgets = ({ type }) => {
    const [plugin_updates, setTotal_plugin_updates] = useState({});
    const [active_plugin_list, setActivePlugin_list] = useState({});
    const [deactive_plugin_list, setDeactivePlugin_list] = useState({});
    const [loggedinuser_list, setLoggedInuser_list] = useState({});
    const [loggedoutuser_list, setLoggedoutuser_list] = useState({});
    const [modalOpen, setModalOpen] = useState(false);
    const [modalContent, setModalContent] = useState({
        title: '',
        content: null
    });

    const openModal = (title, content) => {
        setModalContent({
            title,
            content
        });
        setModalOpen(true);
    };

    const closeModal = () => {
        setModalOpen(false);
    };

    const fetchData = () => {
        wp.ajax.send('wpnts_dashboard_data', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                const total_updates = response.tables;

                // Adding plugin list and activation all to show total plugin update
                setTotal_plugin_updates(total_updates);
                // Seperaterly addin plugin list of active to show the activated plugin name
                total_updates.wpnts_activated_plugins.forEach((plugin, index) => {
                    const firstPart = plugin.split('/')[0]; // Get the first part of the plugin name
                    const byIndex = plugin.indexOf(" by ");
                    const secondPart = byIndex !== -1 ? plugin.slice(byIndex + 4) : "";
                    setActivePlugin_list(prevList => ({ ...prevList, [index]: `${firstPart} : ${secondPart}` }));

                });

                // Seperaterly addin plugin list of deactive to show the deactivated plugin name
                total_updates.wpnts_deactivated_plugins.forEach((plugin, index) => {
                    const firstPart = plugin.split('/')[0]; // Get the first part of the plugin name
                    const byIndex = plugin.indexOf(" by ");
                    const secondPart = byIndex !== -1 ? plugin.slice(byIndex + 4) : "";
                    setDeactivePlugin_list(prevList => ({ ...prevList, [index]: `${firstPart} : ${secondPart}` }));

                });

                // Login info 
                total_updates.wpnts_user_login_info.forEach((user, index) => {
                    // console.log(user.action)
                    if (user.action === 'login') { // Check if the action is 'login'
                        const loginTimestamp = new Date(user.timestamp * 1000); // Convert Unix timestamp to JS Date object
                        const formattedLoginTime = loginTimestamp.toLocaleString(); // Format the login time

                        // Set the user data in the loggedinuser_list state
                        setLoggedInuser_list(prevList => ({
                            ...prevList,
                            [index]: `${user.user} - Logged in at ${formattedLoginTime}`
                        }));
                    }
                    if (user.action === 'logout') {
                        const loginTimestamp = new Date(user.timestamp * 1000); // Convert Unix timestamp to JS Date object
                        const formattedLoginTime = loginTimestamp.toLocaleString(); // Format the login time

                        // Set the user data in the loggedinuser_list state
                        setLoggedoutuser_list(prevList => ({
                            ...prevList,
                            [index]: `${user.user} - Logged out at ${formattedLoginTime}`
                        }));
                    }
                });

            },
            error(error) {
                console.error(error);
            },
        });
    };
    useEffect(() => {
        fetchData();
        const intervalId = setInterval(fetchData, 5000);
        return () => clearInterval(intervalId);
    }, []);

    /**
     * Switch 
     */
    let data;
    const percentage = 0;
    switch (type) {
        case "total_plugin_update":
            data = {
                title: "Plugin Update",
                class: 'total_plugin_update',
                total: plugin_updates.total_plugin_updates ?? <CircularProgress />,
                isPercantage: false,
                activeContent: true,
                content: "Shows remaning plugin which need to update. Makesure to active 'plugin update' from 'Site settings panel' on the settings admin menu",
                link: "Total number of plugins need to be updated",
                url: `${appLocalizer.homeUrl}/plugins.php`,
                icon: (
                    <ExtensionIcon className='wcs_icon' style={{ color: "#464587" }} />
                ),
                hasDetailModal: false
            };
            break;
        case "lat_active_plugin_name":
            const activePluginItems = Object.values(active_plugin_list).map((plugin, index) => (
                <li className='lat_of_active_plug' key={index}>{plugin}</li>
            ));

            data = {
                title: "Today activaited pluigin",
                class: 'lat_active_plugin_name',
                total: active_plugin_list ? (
                    <ol className='lat_active_plugin_name'>
                        {activePluginItems}
                    </ol>
                ) : (
                    <CircularProgress />
                ),
                isPercantage: false,
                activeContent: true,
                content: "Last activated plugin between 24 hours with who active the plugin (User name). Data will automatically reset after 24 hours. Makesure to active 'plugin activation/deactivation' from 'Site settings panel' on the settings admin menu",
                icon: (
                    <Person3Icon className='wcs_users_icon' style={{ color: "black" }} />
                ),
                hasDetailModal: true,
                modalContent: (
                    <div className="detailed-active-plugins">
                        <h3>Active Plugins in Last 24 Hours</h3>
                        <ol className='modal-active-plugin-list'>
                            {activePluginItems}
                        </ol>
                    </div>
                )
            };
            break;
        case "total_deactivaed_plugin":
            const deactivePluginItems = Object.values(deactive_plugin_list).map((plugin, index) => (
                <li className='lat_of_active_plug' key={index}>{plugin}</li>
            ));

            data = {
                title: "Today deactivated pluigin",
                class: 'total_deactivaed_plugin',
                total: deactive_plugin_list ? (
                    <ol className='lat_active_plugin_name'>
                        {deactivePluginItems}
                    </ol>
                ) : <CircularProgress />,
                isPercantage: false,
                activeContent: true,
                content: "Last deactivated plugin between 24 hours with who deactivated the plugin (User name). Data will automatically reset after 24 hours. Makesure to active 'plugin activation/deactivation' from 'Site settings panel' on the settings admin menu",
                icon: (
                    <SettingsInputHdmiIcon className='wcs_resolve_icon' style={{ color: "#31522a" }} />
                ),
                hasDetailModal: true,
                modalContent: (
                    <div className="detailed-deactive-plugins">
                        <h3>Deactivated Plugins in Last 24 Hours</h3>
                        <ol className='modal-deactive-plugin-list'>
                            {deactivePluginItems}
                        </ol>
                    </div>
                )
            };
            break;
        case "todays_who_logged":
            const loggedUsers = Object.values(loggedinuser_list);
            const loggedUserItems = loggedUsers.map((user, index) => (
                <p className='stat-logininfo modal-login-item' key={index}>➡️ {user}</p>
            ));

            data = {
                title: "Today sign-in logs",
                class: 'todays_who_logged',
                total: loggedUsers.map((user, index) => (
                    <span className='stat-logininfo' key={index}>➡️ {user}</span>
                )),
                isPercantage: false,
                count: loggedUsers.length.toString(),
                activeContent: true,
                content: "Last logged in user name with time between 24 hours. Data will automatically reset after 24 hours. Makesure to active 'Login/Logout alert' from 'Site settings panel' on the settings admin menu",
                icon: (
                    <SupportAgentIcon className='wcs_staff_icon' style={{ color: "black" }} />
                ),
                hasDetailModal: true,
                modalContent: (
                    <div className="detailed-login-info">
                        <h3>User Sign-in Logs (Last 24 Hours)</h3>
                        <div className='modal-login-list'>
                            {loggedUserItems.length > 0 ? loggedUserItems : <p>No login activity in the last 24 hours</p>}
                        </div>
                    </div>
                )
            };
            break;

        case "todays_who_out":
            const loggedOutUsers = Object.values(loggedoutuser_list);
            const loggedOutUserItems = loggedOutUsers.map((user, index) => (
                <p className='stat-logininfo modal-logout-item' key={index}>➡️ {user}</p>
            ));

            data = {
                title: "Today sign-out logs",
                class: 'todays_who_out',
                total: loggedOutUsers.map((user, index) => (
                    <span className='stat-logininfo' key={index}>➡️ {user}</span>
                )),
                isPercantage: false,
                count: loggedOutUsers.length.toString(),
                activeContent: true,
                content: "Last logged out user name with time between 24 hours. Data will automatically reset after 24 hours. Makesure to active 'Login/Logout alert' from 'Site settings panel' on the settings admin menu",
                icon: (
                    <Person3Icon className='wcs_staff_icon' style={{ color: "black" }} />
                ),
                hasDetailModal: true,
                modalContent: (
                    <div className="detailed-logout-info">
                        <h3>User Sign-out Logs (Last 24 Hours)</h3>
                        <div className='modal-logout-list'>
                            {loggedOutUserItems.length > 0 ? loggedOutUserItems : <p>No logout activity in the last 24 hours</p>}
                        </div>
                    </div>
                )
            };
            break;

        default:
            break;
    }

    return (
        <div className='wcs_widget wcs_widgets_free'>
            <div className="wcs_left">
                {data.activeContent === true &&
                    <Tippy content={data.content}>
                        <span className="wcs_title">
                            {data.title}
                            <HelpOutlineIcon className='wcs_tooltip_icon' />

                        </span>
                    </Tippy>}
                {data.hasDetailModal && (
                    <IconButton
                        className="expand-details-btn"
                        aria-label="show details"
                        onClick={() => openModal(data.title, data.modalContent)}
                        size="small"
                    >
                        <FullscreenIcon fontSize="small" />
                    </IconButton>
                )}
                {data.activeContent === false &&
                    <span className="wcs_title">
                        {data.title}
                        {data.hasDetailModal && (
                            <IconButton
                                className="expand-details-btn"
                                aria-label="show details"
                                onClick={() => openModal(data.title, data.modalContent)}
                                size="small"
                            >
                                <FullscreenIcon fontSize="small" />
                            </IconButton>
                        )}
                    </span>
                }
                <span className={`wcs_counter list_of_plug ${data.class}`}>{data.total}</span>
                <a target='_blank' href={data.url} className="wcs_link">{data.link}</a>
            </div>
            <div className="wcs_right wec_right_free">
                {data.isPercantage &&
                    <div className="wcs_percentage wcs_positive">
                        <KeyboardArrowUpIcon />
                        {percentage}{data.isPercantage && "P"}
                    </div>
                }

                {data.count &&
                    <div className="wcs_percentage wcs_positive">
                        <KeyboardArrowUpIcon />
                        {data.count}{data.count && "P"}
                    </div>
                }
                <div className="wcs_percentage wcs_positive"></div>

                {data.icon}
            </div>

            <Dialog
                open={modalOpen}
                onClose={closeModal}
                aria-labelledby="detail-dialog-title"
                maxWidth="md"
                fullWidth
            >
                <DialogTitle id="detail-dialog-title">{modalContent.title}</DialogTitle>
                <DialogContent dividers>
                    {modalContent.content}
                </DialogContent>
                <DialogActions>
                    <Button onClick={closeModal} color="primary">
                        Close
                    </Button>
                </DialogActions>
            </Dialog>
        </div>
    )
}

export default WCSWidgets