import React, { useState, useEffect } from "react";
import { isPro, getNonce, getNoticeData, systemInfo, getActivitylogs } from '../../Helpers';
import DataTable from 'datatables.net-react';
import DT from 'datatables.net-dt';
import './../../../node_modules/datatables.net-dt/css/dataTables.dataTables.min.css';
import NotificationsActiveIcon from '@mui/icons-material/NotificationsActive';
import unknown from '../../../assets/icons/support/unknown.png'
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import WarningIcon from '@mui/icons-material/Warning';
import WarningAmberIcon from '@mui/icons-material/WarningAmber';

import { format } from 'date-fns';
import "./activity.scss"


const Activity = () => {
    const [activityData, setActivityData] = useState(getActivitylogs());
    const [filters, setFilters] = useState({
        severity: '',
        user: '',
        eventType: '',
        dateRange: 'all-time',
        user_role: '',
    });


    const tableOptions = {
        order: [],
        pageLength: 30,
        responsive: true,
        lengthMenu: [
            [1, 5, 10, 15, 30, 50, 100, -1],
            [1, 5, 10, 15, 30, 50, 100, "All"],
        ],
    };

    DataTable.use(DT);

    const fetchData = () => {
        wp.ajax.send('activity_table', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                setActivityData(response.activity_logs);
            },
            error(error) {
                console.error(error);
            },
        });
    };

    const handleFilterChange = (e) => {
        setFilters({
            ...filters,
            [e.target.name]: e.target.value,
        });
    };

    const clearFilters = () => {
        setFilters({
            severity: '',
            user: '',
            eventType: '',
            dateRange: 'all-time',
            user_role: '',
        });
    };

    const applyFilters = (data) => {
        const today = new Date();
        const startOfToday = new Date(today.setHours(0, 0, 0, 0));
        const startOfYesterday = new Date(startOfToday);
        startOfYesterday.setDate(startOfYesterday.getDate() - 1);

        const startOfWeek = new Date(startOfToday);
        startOfWeek.setDate(startOfWeek.getDate() - today.getDay());

        const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

        return data.filter(item => {
            const logDate = new Date(item.date);

            const dateFilter =
                filters.dateRange === 'all-time' ||
                (filters.dateRange === 'today' && logDate >= startOfToday) ||
                (filters.dateRange === 'yesterday' &&
                    logDate >= startOfYesterday &&
                    logDate < startOfToday) ||
                (filters.dateRange === 'week' && logDate >= startOfWeek) ||
                (filters.dateRange === 'month' && logDate >= startOfMonth);

            const roleFilter =
                !filters.user_role ||
                filters.user_role === "unknown" && (!item.user_role || item.user_role === "") ||
                (item.user_role && item.user_role.toLowerCase() === filters.user_role.toLowerCase());

            return (
                dateFilter &&
                roleFilter &&
                (!filters.severity || item.severity.includes(filters.severity)) &&
                (!filters.user || item.user.includes(filters.user)) &&
                (!filters.eventType || item.event_type.includes(filters.eventType))
            );
        });
    };




    useEffect(() => {
        fetchData();
        const intervalId = setInterval(fetchData, 8000);
        return () => clearInterval(intervalId);
    }, []);

    const getUniqueOptions = (data, field) => {
        return [...new Set(data.map(item => item[field]))];
    };

    const severityOptions = getUniqueOptions(activityData, 'severity');
    const userOptions = getUniqueOptions(activityData, 'user');
    const eventTypeOptions = getUniqueOptions(activityData, 'event_type');

    const columns = [
        { title: 'ID', data: 'id', width: '3%' },
        { title: 'Severity', data: 'severity', width: '5%' },
        {
            title: 'Date',
            data: 'date',
            width: '10%',
            render: (data, type, row) => {
                if (type === 'display' && data) {
                    return format(new Date(data), 'MMMM d, yyyy h:mm:ss a');
                }
                return data;
            }
        },
        // { title: 'IP', data: 'ip', width: '10%' },
        {
            title: 'IP',
            data: 'ip',
            width: '10%',
            render: (data, type, row) => {
                const { ip } = row;
                const displayIp = ip || 'Not detected';
                return `
                    <div class="ip-cell">
                        <div class="user-ip">
                            <span>${displayIp}</span>
                        </div>
                        <button class="view-button" onclick="window.open('https://whatismyipaddress.com/ip/${displayIp}', '_blank')">Find</button>
                    </div>
                `;
            }
        },

        // { title: 'User', data: 'user', width: '10%' },

        {
            title: 'User',
            data: 'user',
            width: '10%',
            render: (data, type, row) => {
                const { thumb, user, user_role } = row;
                // console.log(thumb);
                const displayName = user || 'No Name';
                const displayRole = user_role || 'Unknown';
                const thumbSrc = thumb ? thumb : unknown;

                return `
                    <div class="user-cell">
                        <img src="${thumbSrc}" alt="${displayName}" class="user-thumb" />
                        <div class="user-info">
                            <span class="user-name">${displayName}</span>
                            <span class="user-role">${displayRole}</span>
                        </div>
                    </div>
                `;
            },
        },

        { title: 'Event Type', data: 'event_type', width: '10%' },
        {
            title: 'Message',
            data: 'message',
            width: '30%',
            render: function (data, type, row) {
                if (type === 'display') {
                    return data.replace(/(\r\n|\n|\r)/g, '<br>');
                }
                return data;
            },
            className: 'message-column'
        },
    ];


    return (
        <div className="activity-log" id="systemInfo">
            <div className="acb_left">
                <h3 className="system-header">Activity log <NotificationsActiveIcon className="system-header-icon" /> </h3>
                <br />

                <div className="activity-filters">

                    <select
                        name="dateRange"
                        value={filters.dateRange}
                        onChange={handleFilterChange}
                    >
                        <option value="all-time">All Time</option>
                        <option value="today">Today</option>
                        <option value="yesterday">Yesterday</option>
                        <option value="week">This Week</option>
                        <option value="month">This Month</option>
                    </select>

                    <select
                        name="user_role"
                        value={filters.user_role}
                        onChange={handleFilterChange}
                    >
                        <option value="">All Roles</option>
                        <option value="administrator">Administrator</option>
                        <option value="editor">Editor</option>
                        <option value="author">Author</option>
                        <option value="guest">Guest</option>
                        <option value="contributor">Contributor</option>
                        <option value="subscriber">Subscriber</option>
                        <option value="unknown">Unknown</option>
                    </select>

                    <select
                        name="severity"
                        value={filters.severity}
                        onChange={handleFilterChange}
                    >
                        <option value="">Filter by Severity</option>
                        {severityOptions.map((option, index) => (
                            <option key={index} value={option}>{option}</option>
                        ))}
                    </select>

                    <select
                        name="user"
                        value={filters.user}
                        onChange={handleFilterChange}
                    >
                        <option value="">Filter by User</option>
                        {userOptions.map((option, index) => (
                            <option key={index} value={option}>{option}</option>
                        ))}
                    </select>

                    <select
                        name="eventType"
                        value={filters.eventType}
                        onChange={handleFilterChange}
                    >
                        <option value="">Filter by Event Type</option>
                        {eventTypeOptions.map((option, index) => (
                            <option key={index} value={option}>{option}</option>
                        ))}
                    </select>

                    <button onClick={clearFilters}>Clear Filters</button>
                </div>

                <div className="activity-table">
                    <DataTable
                        data={applyFilters(activityData)}
                        columns={columns}
                        responsive={true}
                        options={tableOptions}
                        className="activity-table-display"
                    /* slots={{
                        6: (data, row) => (
                            <button>Block IP</button>
                        )
                    }} */
                    />
                </div>
            </div>
        </div>
    );
}


export default Activity
