import React, { useState, useEffect } from 'react'
import WCSWidgets from '../Components/Widgets/WCSWidgets';
import WCSFeatured from '../Components/Feature/WCSFeatured';
import WCSChart from '../Components/Charts/WCSChart';
import Traffic from '../Components/Traffic/Traffic';
import Activeuser from '../Components/Activeuser/Activeuser';
import SystemInfo from '../Components/SystemInfo/SystemInfo';
import DashboardHeader from '../Components/DashboardHeader/DashboardHeader';
import SevenDayRollingAnalytics from '../Components/Analytics/SevenDayRollingAnalytics';
import { DashboardDataProvider, useDashboardData } from '../contexts/DashboardDataContext';
import { useDataRefreshIndicator } from '../hooks/useDataRefreshIndicator';
import { isPro } from '../Helpers';

import "./dashboard.scss";
import "./dashboard-enhanced.scss";

// Inner Dashboard component that uses the context
const DashboardContent = () => {
  const {
    isLoading,
    noticeSettings,
    dashboardData,
    error,
    lastUpdated,
    getAnalyticsSettings
  } = useDashboardData();

  const showRefreshIndicator = useDataRefreshIndicator(lastUpdated);

  const [showEmptyMessage, setShowEmptyMessage] = useState(true);

  // Get analytics settings from context
  const analyticsData = getAnalyticsSettings();
  const analyticsSettings = {
    system_overview: analyticsData?.system_overview !== undefined ? analyticsData.system_overview : true,
    activity_analytics: analyticsData?.activity_analytics !== undefined ? analyticsData.activity_analytics : true,
    security_monitoring: analyticsData?.security_monitoring !== undefined ? analyticsData.security_monitoring : true,
    user_activity: analyticsData?.user_activity !== undefined ? analyticsData.user_activity : true,
    visitors_traffic_list: analyticsData?.visitors_traffic_list !== undefined ? analyticsData.visitors_traffic_list : true,
    advance_system_info_panel: analyticsData?.advance_system_info_panel !== undefined ? analyticsData.advance_system_info_panel : true,
    seven_day_rolling_analytics: analyticsData?.seven_day_rolling_analytics !== undefined ? analyticsData.seven_day_rolling_analytics : true,
  };

  // Check if all widgets are disabled
  const areAllWidgetsDisabled = () => {
    return !Object.values(analyticsSettings).some(value => value === true);
  };

  // Show loading spinner while fetching settings
  if (isLoading) {
    return (
      <div className="wcs_home">
        <div className="wcs_homeContainer">
          <DashboardHeader dashboardData={dashboardData} noticeSettings={noticeSettings} />
          <div className="dashboard-loading">
            <div className="loading-spinner"></div>
            <div className="loading-text">
              <h3>Preparing Your Dashboard</h3>
              <p>Loading analytics settings and system data...</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Show error state if there's an error
  if (error) {
    return (
      <div className="wcs_home">
        <div className="wcs_homeContainer">
          <DashboardHeader dashboardData={dashboardData} noticeSettings={noticeSettings} />
          <div className="dashboard-error">
            <div className="error-content">
              <h3>Error Loading Dashboard</h3>
              <p>There was an error loading the dashboard data. Please try refreshing the page.</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Show empty state message if all widgets are disabled
  const allDisabled = areAllWidgetsDisabled();

  return (
    <div className="wcs_home">
      <div className="wcs_homeContainer">
        <DashboardHeader dashboardData={dashboardData} noticeSettings={noticeSettings} />

        {/* Data Refresh Indicator */}
        {showRefreshIndicator && (
          <div className="data-refresh-indicator visible">
            <span className="refresh-icon">🔄</span>
            Data refreshed
          </div>
        )}

        <div className="dashboard_active" id='wcs_dashboard'>
          <div className="wcs_dashboard_cls">

            {/* Empty State Message - Shows when all widgets are disabled */}
            {allDisabled && showEmptyMessage && (
              <div className="dashboard-empty-state">
                <div className="empty-state-icon">
                  <svg width="120" height="120" viewBox="0 0 120 120" fill="none">
                    <circle cx="60" cy="60" r="50" stroke="#E5E7EB" strokeWidth="2" strokeDasharray="8 8" />
                    <path d="M60 30V60L75 75" stroke="#9CA3AF" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
                    <circle cx="60" cy="60" r="5" fill="#9CA3AF" />
                  </svg>
                </div>
                <h2 className="empty-state-title">Dashboard Widgets Disabled</h2>
                <p className="empty-state-description">
                  All analytics sections are currently turned off. Enable widgets to view your dashboard data.
                </p>
                <div className="empty-state-action">
                  <svg className="info-icon" width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
                    <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                  </svg>
                  <span>Go to <strong>Configuration → Analytics Configuration Panel</strong> to enable widgets</span>
                </div>
                <button
                  className="empty-state-dismiss"
                  onClick={() => setShowEmptyMessage(false)}
                  aria-label="Dismiss message"
                >
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                    <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z" />
                  </svg>
                </button>
              </div>
            )}

            {/* System Overview Section */}
            {analyticsSettings.system_overview && (
              <section className="dashboard-section overview-section">
                <div className="section-header">
                  <h2 className="section-title">System Overview</h2>
                  <p className="section-subtitle">Real-time monitoring of your WordPress site</p>
                </div>

                <div className="wcs_widgets wcs_free wcs-status">
                  <div className="widget_row widget_row_3 key-metrics">
                    <WCSWidgets type="total_plugin_update" dashboardData={dashboardData} />
                    <WCSWidgets type="lat_active_plugin_name" dashboardData={dashboardData} />
                    <WCSWidgets type="total_deactivaed_plugin" dashboardData={dashboardData} />
                  </div>
                </div>
              </section>
            )}

            {/* Activity Analytics Section */}
            {analyticsSettings.activity_analytics && (
              <section className="dashboard-section analytics-section">
                <div className="section-header">
                  <h2 className="section-title">Activity Analytics</h2>
                  <p className="section-subtitle">Comprehensive view of user activities and login patterns</p>
                </div>

                <div className="wcs_charts wcs_free enhanced-chart">
                  <WCSChart dashboardData={dashboardData} />
                </div>
              </section>
            )}

            {/* Security Monitoring Section */}
            {analyticsSettings.security_monitoring && (
              <section className="dashboard-section security-section">
                <div className="section-header">
                  <h2 className="section-title">Security Monitoring</h2>
                  <p className="section-subtitle">Track failed logins and security threats</p>
                </div>

                <div className="wcs_widgets wcs_free wcs-status">
                  <div className="widget_row widget_row_2 security-widgets">
                    <WCSWidgets type="failed_login_summary" dashboardData={dashboardData} />
                    <WCSWidgets type="failed_login_chart" dashboardData={dashboardData} />
                  </div>
                </div>
              </section>
            )}

            {/* User Activity Section */}
            {analyticsSettings.user_activity && (
              <section className="dashboard-section activity-section">
                <div className="section-header">
                  <h2 className="section-title">User Activity</h2>
                  <p className="section-subtitle">Monitor user logins, logouts, and daily activity patterns</p>
                </div>

                <div className="wcs_widgets wcs_free wcs-status">
                  <div className="widget_row widget_row_3 activity-widgets">
                    <WCSWidgets type="todays_who_logged" dashboardData={dashboardData} />
                    <WCSWidgets type="todays_who_out" dashboardData={dashboardData} />
                    <WCSFeatured dashboardData={dashboardData} />
                  </div>

                  <div className="widget_row widget_row_2 activity-analytics">
                    <WCSWidgets type="daily_login_activity" dashboardData={dashboardData} />
                    <WCSWidgets type="security_threat_level" dashboardData={dashboardData} />
                  </div>
                </div>
              </section>
            )}

            {/* 7-Day Rolling Analytics Section */}
            {analyticsSettings.seven_day_rolling_analytics && (
              <section className="dashboard-section rolling-analytics-section">
                <div className="section-header">
                  <h2 className="section-title">7-Day Rolling Analytics</h2>
                  <p className="section-subtitle">Advanced login/logout tracking with detailed insights and automatic cleanup</p>
                </div>

                <SevenDayRollingAnalytics dashboardData={dashboardData} />
              </section>
            )}

            {/* Visitors Traffic List Section */}
            {analyticsSettings.visitors_traffic_list && (
              <section className="dashboard-section traffic-section">
                <div className="section-header">
                  <h2 className="section-title">Visitors Traffic List</h2>
                  <p className="section-subtitle">Real-time visitor data and traffic analytics</p>
                </div>

                <div className="system-info-vertical">
                  <div className="system-card-full">
                    <Activeuser />
                  </div>

                  <div className="system-card-full">
                    <Traffic />
                  </div>
                </div>
              </section>
            )}

            {/* Advanced System Info Panel Section */}
            {analyticsSettings.advance_system_info_panel && (
              <section className="dashboard-section advanced-system-section">
                <div className="section-header">
                  <h2 className="section-title">Advanced System Information</h2>
                  <p className="section-subtitle">Comprehensive system diagnostics and detailed server information</p>
                </div>

                <div className="system-info-vertical">
                  <div className="system-card-full">
                    <SystemInfo />
                  </div>
                </div>
              </section>
            )}

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

// Main Dashboard component with provider
const Dashboard = () => {
  return (
    <DashboardDataProvider>
      <DashboardContent />
    </DashboardDataProvider>
  );
}

export default Dashboard