import MoreVertTwoTone from '@mui/icons-material/MoreVert'
import { CircularProgressbar } from 'react-circular-progressbar';
import CircularProgress from '@mui/material/CircularProgress';
import 'react-circular-progressbar/dist/styles.css';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import React, { useState, useEffect } from "react";
import { getNonce, getDashboardData } from '../../Helpers';
import './featured.scss'

const WCSFeatured = () => {
    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 [dashboard, setDashboard] = useState(getDashboardData());
    const [site_helgth, setSite_helgth] = useState({});

    // Fetch data
    const fetchData = () => {
        wp.ajax.send('wpnts_dashboard_data', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                setDashboard(response.tables);
                setSite_helgth(response.tables);
            },
            error(error) {
                console.error(error);
            },
        });
    };

    /**
     * @returns Calculate total site status score
     * 
     * 80-100%: Good condition, no immediate actions required.
     * 50-80%: Fair condition, improvements recommended.
     * 0-50%: Critical condition, immediate action needed.
     * 100% health = all good
     * Good gives full points, recommended gives half points, critical reduces score drastically
     */

    const calculateTotalScore = () => {

        if (!site_helgth.wpnts_site_health) return 0;

        const { good = 0, recommended = 0, critical = 0 } = site_helgth.wpnts_site_health;

        const totalPossiblePoints = (good * 100) + (recommended * 50); // Only count good and recommended for total possible points
        const achievedPoints = (good * 100) + (recommended * 50) - (critical * 100); // Subtract critical points

        // Calculate total score as a percentage
        const totalScore = totalPossiblePoints > 0 ? (achievedPoints / totalPossiblePoints) * 100 : 0;

        return totalScore > 0 ? totalScore : 0; // Ensure non-negative score

    };

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

    const totalScore = calculateTotalScore();

    // Function to get message based on the score.
    const getHealthMessage = () => {
        if (totalScore >= 80) {
            return {
                message: "➡️ Your site is in excellent health! No immediate actions are required. 😃",
                className: "good-health"
            };
        } else if (totalScore >= 50 && totalScore < 80) {
            return {
                message: "➡️ Your site is in fair condition. Some recommendations should be followed to improve site health. 🤨",
                className: "warning-health"
            };
        } else {
            return {
                message: "➡️ Your site health is critical. Immediate action is required to resolve issues. 😟",
                className: "critical-health"
            };
        }
    };



    return (
        <div className='wcs_featured'>
            <div className="wcs_featureds">
                <div className="wcs_top">
                    <h1 className="wcs_title">{adminURL}- Health Status</h1>
                </div>
                <div className="wcs_bottom">
                    <div className="wcs_featuredChart">
                        <CircularProgressbar value={totalScore} text={`${totalScore.toFixed(1)}%`} strokeWidth={5} />
                    </div>

                    <p className="wcs_title">health score</p>
                    <br />
                    <div className="wcs_summary">
                        <div className="wcs_item">
                            <div className="itemTitle">Good</div>
                            <div className="itemResult positive">
                                <KeyboardArrowUpIcon fontSize='small' />
                                <div className="resultAmount">{site_helgth.wpnts_site_health ? site_helgth.wpnts_site_health.good : <CircularProgress />}</div>
                            </div>
                        </div>
                        <div className="wcs_item">
                            <div className="itemTitle">Recommended</div>
                            <div className="itemResult positive">
                                <KeyboardArrowUpIcon fontSize='small' />
                                <div className="resultAmount">{site_helgth.wpnts_site_health ? site_helgth.wpnts_site_health.recommended : ''}</div>
                            </div>
                        </div>
                        <div className="wcs_item">
                            <div className="itemTitle">Critical</div>
                            <div className="itemResult negative">
                                <KeyboardArrowDownIcon fontSize='small' />
                                <div className="resultAmount">{site_helgth.wpnts_site_health ? site_helgth.wpnts_site_health.critical : ''}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Dynamic message based on health score */}
            {site_helgth.wpnts_site_health && (
                <>
                    <p className={`wcs_healthMessage ${getHealthMessage().className}`}>
                        {getHealthMessage().message}
                    </p>
                    <h5>Recommended list: <a href={`${visitURL}/wp-admin/site-health.php`} target="_blank" rel="noopener noreferrer">view</a></h5>
                </>
            )}
        </div>
    )
}

export default WCSFeatured