import React, { useState, useEffect } from "react";
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
import CircularProgress from '@mui/material/CircularProgress';
import SupervisedUserCircleIcon from '@mui/icons-material/SupervisedUserCircle';
import { getvisitorData, getNonce, isPro, get_current_user_id } from '../../Helpers';
import orderStatus from '../../../assets/order-status.gif'
import { DataGrid } from '@mui/x-data-grid';
import Box from '@mui/material/Box';
import Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css';
import NoticeModal from '../NoticeModal/NoticeModal';
import "./activeuser.scss";

const Activeuser = () => {
    const [modalOpen, setModalOpen] = useState(false);
    const [loggedinuserList, setLoggedinuserList] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [filteredRows, setFilteredRows] = useState([]);

    const proData = isPro();
    const allConditionsMet = proData;
    const user_id = get_current_user_id();

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

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

    const loginfetchData = () => {
        wp.ajax.send('get_active_logged_in_users', {
            data: { nonce: getNonce() },
            success(response) {
                const userList = response.user_names;
                const users = Object.keys(userList).map(userId => ({
                    id: userId,
                    username: userList[userId],
                    login_time: response.login_time[userId],
                    status: "Active"
                }));
                setLoggedinuserList(users);
            },
            error(error) { console.error(error); }
        });
    };

    useEffect(() => {
        loginfetchData();
        const loginintervalId = setInterval(loginfetchData, 5000);
        return () => clearInterval(loginintervalId);

    }, [allConditionsMet]);


    /**
    * 
    * @param {Logged out} id 
    * @param {*} event 
    */
    const handleLogoutUser = (id, event) => {
        event.stopPropagation();

        if (!allConditionsMet) {
            // setModalOpen(true)
            setModalConfig({
                isOpen: true,
                type: 'premium',
                title: '🚀 Oops! This is a Premium Feature',
                message: 'Evaluate the features and select a bundle based on your needs.',
                onConfirm: () => {
                    window.open('https://functiondeck.com/pricing/', '_blank');
                    closeModal();
                },
                confirmText: 'Get Started',
                declineText: 'Maybe Later'
            });

            return;
        }


        setModalConfig({
            isOpen: true,
            type: 'confirmation',
            title: 'Confirm Kickout',
            message: 'Are you sure you want to Kickout this user forcefully? He will be logout from your site.',
            onConfirm: () => {
                wp.ajax.send('wpnts_logoutUser_forcefully', {
                    data: {
                        nonce: getNonce(),
                        id: id
                    },
                    success(response) {
                        if (response.status === 'success') {
                            // Update active users data
                            wp.ajax.send('update_active_users_data', {
                                data: {
                                    nonce: getNonce(),
                                    user_id: id
                                },
                                success() {
                                    // Refetch login data
                                    loginfetchData();
                                },
                                error(error) {
                                    console.error(error);
                                },
                            });

                            // Update status in UI
                            setLoggedinuserList(prevList => prevList.map(user => {
                                if (user.id === id) {
                                    return { ...user, status: 'Inactive' };
                                }
                                return user;
                            }));

                            // Show success toast
                            setModalConfig({
                                isOpen: true,
                                type: 'toast',
                                title: 'Logged Out!',
                                message: 'The user has been Kickout out forcefully.',
                                position: 'top-right'
                            });

                            // Auto close the toast after 3 seconds
                            setTimeout(closeModal, 3000);
                        }
                    },
                    error(error) {
                        console.error(error);
                        // Show error toast
                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Error!',
                            message: 'Failed to Kickout the user.',
                            position: 'top-right'
                        });

                        // Auto close the toast after 3 seconds
                        setTimeout(closeModal, 3000);
                    },
                });

                // Close the confirmation modal immediately
                closeModal();
            },
            confirmText: 'Yes, Kickout!',
            declineText: 'Cancel'
        });
    };



    const userColumns = [
        {
            field: "id",
            headerName: "UID",
            flex: 0.5,
        },


        {
            field: "username",
            headerName: "Name",
            flex: 1,
            valueGetter: (params) => {
                if (user_id === null) {
                    return params.row.username;
                }
                return params.row.id === user_id ? `${params.row.username} (me)` : params.row.username;
            }
        },



        {
            field: "login_time",
            headerName: "Login at",
            flex: 1,
            valueFormatter: (params) => new Date(params.value * 1000).toLocaleString(),
        },

        {
            field: 'time_spent',
            headerName: 'Time Spent',
            flex: 1,
            valueFormatter: (params) => {

                const user = loggedinuserList.find(user => user.id === params.id);
                if (!user || typeof user.login_time === 'undefined') {
                    return "Not available";
                }

                const loginTime = user.login_time * 1000;
                const currentTime = new Date().getTime();
                const timeDifference = currentTime - loginTime;
                const minutes = Math.floor(timeDifference / (1000 * 60));
                const hours = Math.floor(minutes / 60);

                if (isNaN(timeDifference) || isNaN(minutes) || isNaN(hours)) {
                    return "Not available";
                }

                if (hours > 0) {
                    return `${hours} hour${hours > 1 ? 's' : ''}`;
                } else {
                    return `${minutes} minute${minutes > 1 ? 's' : ''}`;
                }
            },
        },


        {
            field: 'status',
            headerName: 'Status',
            flex: 1,
            renderCell: (params) => (
                <div className={params.row.status === 'Active' ? 'active-user-status' : 'inactive-user-status'}>
                    {params.row.status}
                </div>
            ),
        }
    ];

    /**
     * Action column
     */
    const actionColumns = [
        {
            field: "action",
            headerName: "ACTION",
            flex: 0.5,
            renderCell: (params) => (
                <div className="wpx_cellAction">
                    <div
                        className="wpx_deleteButton"
                        onClick={(event) => handleLogoutUser(params.id, event)}
                    >
                        Kickout
                    </div>
                </div>
            ),
        },
    ];




    const handleSearchChange = (event) => {
        setSearchTerm(event.target.value);
    };

    useEffect(() => {
        if (loggedinuserList.length > 0) {
            const filtered = loggedinuserList.filter(row =>
                row.username.toLowerCase().includes(searchTerm.toLowerCase())
            );
            setFilteredRows(filtered);
        }
    }, [loggedinuserList, searchTerm]);



    return (
        <div className="acb_traffic" id='acb_traffic'>
            <div className="acb_left">
                <h2 className="title-active-user">Active user list </h2>
                <h3 className="review-case-title active-user">
                    <SupervisedUserCircleIcon className='PlayCircleIcon' />
                    Total active: <span className="active-number">
                        {loggedinuserList.length > 0 ? loggedinuserList.length : <CircularProgress />}
                    </span>
                </h3>

                <br />

                <input
                    type="text"
                    placeholder="Search..."
                    value={searchTerm}
                    onChange={handleSearchChange}
                    className="wpx-search-leads"
                />

                <div className="subs-list">
                    <Box sx={{ height: 300, width: '100%' }}>
                        <DataGrid
                            rows={filteredRows}
                            columns={userColumns.concat(actionColumns)}
                            pageSize={5}
                        />
                    </Box>
                </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 Activeuser;
