﻿import React, { useEffect, useRef } from 'react';
import { 
  Users, 
  MessageCircle, 
  Shield, 
  Activity,
  TrendingUp,
  AlertTriangle,
  RefreshCw,
  AlertCircle,
  BarChart3,
  Settings,
  UserCheck
} from 'lucide-react';
import { useApp } from '../context/AppContext';
import { useAuth } from '../context/AuthContext';
import AnalyticsCharts from '../components/AnalyticsCharts';

const Dashboard: React.FC = () => {
  const { 
    dashboardStats, 
    dashboardLoading, 
    dashboardError, 
    fetchDashboardStats,
    analyticsData,
    analyticsLoading,
    analyticsError,
    fetchAnalytics
  } = useApp();
  const { user, isSuperAdmin, isAdmin, hasPermission, hasAnyPermission } = useAuth();
  
  // Ref to track last API call time to prevent rapid successive calls
  const lastFetchTime = useRef<number>(0);
  const FETCH_COOLDOWN = 2000; // 2 seconds cooldown

  // Throttled refresh function to prevent rapid successive API calls
  const throttledRefresh = () => {
    const now = Date.now();
    if (now - lastFetchTime.current < FETCH_COOLDOWN) {
      console.log('Refresh throttled, please wait...');
      return;
    }
    
    lastFetchTime.current = now;
    fetchDashboardStats();
  };

  // Fetch dashboard stats and analytics on component mount
  useEffect(() => {
    console.log('Dashboard component mounted, fetching stats and analytics...');
    
    // Only fetch if not already loading or if there's no data
    if (!dashboardLoading && !dashboardStats) {
    fetchDashboardStats();
    }
    
    if (!analyticsLoading && !analyticsData) {
    fetchAnalytics();
    }
  }, []); // Empty dependency array - only run once on mount

  // Debug logging
  useEffect(() => {
    if (dashboardStats) {
      console.log('Dashboard loaded with', Object.keys(dashboardStats).length, 'data sections');
    }
  }, [dashboardStats]);

  // Role-based stats filtering
  const getFilteredStats = () => {
    const allStats = [
      {
        name: 'Total Contacts',
        value: dashboardStats?.totalContacts?.total_contacts || 0,
        icon: Users,
        color: 'bg-blue-500',
        change: dashboardStats?.totalContacts?.new_contacts_7d ? `+${dashboardStats.totalContacts.new_contacts_7d}` : '+0',
        subtitle: `${dashboardStats?.totalContacts?.active_contacts || 0} active`,
        permission: 'user.read',
        roles: ['Super_admin', 'Admin', 'User']
      },
      {
        name: 'Active Conversations',
        value: dashboardStats?.activeConversations?.total_conversations || 0,
        icon: MessageCircle,
        color: 'bg-green-500',
        change: dashboardStats?.activeConversations?.active_24h ? `+${dashboardStats.activeConversations.active_24h}` : '+0',
        subtitle: `${dashboardStats?.activeConversations?.direct_conversations || 0} direct, ${dashboardStats?.activeConversations?.group_conversations || 0} group`,
        permission: 'conversation.read',
        roles: ['Super_admin', 'Admin', 'User']
      },
      {
        name: 'Online Contacts',
        value: dashboardStats?.onlineContacts?.online_now || 0,
        icon: Activity,
        color: 'bg-yellow-500',
        change: dashboardStats?.onlineContacts?.active_24h ? `+${dashboardStats.onlineContacts.active_24h}` : '+0',
        subtitle: `${dashboardStats?.onlineContacts?.busy_now || 0} busy, ${dashboardStats?.onlineContacts?.offline_now || 0} offline`,
        permission: 'user.read',
        roles: ['Super_admin', 'Admin', 'User']
      },
      {
        name: 'Messages Today',
        value: dashboardStats?.conversationStats?.total_messages_24h || 0,
        icon: BarChart3,
        color: 'bg-purple-500',
        change: dashboardStats?.conversationStats?.unique_senders_24h ? `+${dashboardStats.conversationStats.unique_senders_24h} senders` : '+0',
        subtitle: `${dashboardStats?.conversationStats?.text_messages_24h || 0} text, ${dashboardStats?.conversationStats?.system_messages_24h || 0} system`,
        permission: 'message.read',
        roles: ['Super_admin', 'Admin', 'User']
      },
      {
        name: 'Security Alerts',
        value: dashboardStats?.securityAlerts?.failed_logins_24h || 0,
        icon: Shield,
        color: 'bg-red-500',
        change: dashboardStats?.securityAlerts?.total_activities_24h ? `${dashboardStats.securityAlerts.total_activities_24h} total` : '0 total',
        subtitle: `${dashboardStats?.securityAlerts?.admin_actions_7d || 0} admin actions`,
        permission: 'audit_log.read',
        roles: ['Super_admin', 'Admin']
      },
      {
        name: 'User Management',
        value: dashboardStats?.userStats ? (dashboardStats.userStats.super_admins + dashboardStats.userStats.admins + dashboardStats.userStats.regular_users) : 0,
        icon: UserCheck,
        color: 'bg-indigo-500',
        change: dashboardStats?.userStats?.new_users_30d ? `+${dashboardStats.userStats.new_users_30d}` : '+0',
        subtitle: `${dashboardStats?.userStats?.active_users_7d || 0} active users`,
        permission: 'user.manage_roles',
        roles: ['Super_admin']
      }
    ];

    // Filter stats based on user permissions and role
    return allStats.filter(stat => {
      const hasPermission = stat.permission ? user?.permissions?.includes(stat.permission) : true;
      const hasRole = stat.roles.includes(user?.role || 'User');
      return hasPermission && hasRole;
    });
  };

  const stats = getFilteredStats();


  // Loading state
  if (dashboardLoading) {
    return (
      <div className="p-6 space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">
              {isSuperAdmin() ? 'Super Admin Dashboard' : 
               isAdmin() ? 'Admin Dashboard' : 
               'User Dashboard'}
            </h1>
            <p className="text-sm text-gray-600 mt-1">
              {isSuperAdmin() ? 'Full system access and control' :
               isAdmin() ? 'Administrative panel with management tools' :
               'Your personal dashboard'}
            </p>
          </div>
          <div className="text-right">
            <div className="text-sm text-gray-500">
              Welcome back, {user?.name}
            </div>
            <div className="text-xs text-gray-400">
              {user?.role} • {user?.service_no}
            </div>
          </div>
        </div>
        <div className="flex items-center justify-center h-64">
          <div className="flex items-center space-x-2">
            <RefreshCw className="h-6 w-6 animate-spin text-blue-500" />
            <span className="text-gray-600">Loading dashboard stats...</span>
          </div>
        </div>
      </div>
    );
  }

  // Error state - but still show dashboard with fallback data
  if (dashboardError && !dashboardStats) {
    return (
      <div className="p-6 space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">
              {isSuperAdmin() ? 'Super Admin Dashboard' : 
               isAdmin() ? 'Admin Dashboard' : 
               'User Dashboard'}
            </h1>
            <p className="text-sm text-gray-600 mt-1">
              {isSuperAdmin() ? 'Full system access and control' :
               isAdmin() ? 'Administrative panel with management tools' :
               'Your personal dashboard'}
            </p>
          </div>
          <div className="text-right">
            <div className="text-sm text-gray-500">
              Welcome back, {user?.name}
            </div>
            <div className="text-xs text-gray-400">
              {user?.role} • {user?.service_no}
            </div>
          </div>
        </div>
        
        {/* Show error banner but continue with dashboard */}
        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
          <div className="flex items-center">
            <AlertCircle className="h-5 w-5 text-yellow-600 mr-2" />
            <div>
              <h3 className="text-sm font-medium text-yellow-800">Dashboard data unavailable</h3>
              <p className="text-sm text-yellow-700 mt-1">{dashboardError}</p>
            </div>
            <button
              onClick={throttledRefresh}
              className="ml-auto px-3 py-1 bg-yellow-100 text-yellow-800 rounded text-sm hover:bg-yellow-200 transition-colors disabled:opacity-50"
              disabled={dashboardLoading}
            >
              {dashboardLoading ? 'Retrying...' : 'Retry'}
            </button>
          </div>
        </div>

        {/* Fallback dashboard with zero values */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {[
            { name: 'Total Contacts', value: 0, icon: Users, color: 'bg-blue-500', change: '+0' },
            { name: 'Active Conversations', value: 0, icon: MessageCircle, color: 'bg-green-500', change: '+0' },
            { name: 'Online Contacts', value: 0, icon: Activity, color: 'bg-yellow-500', change: '+0' },
            { name: 'Security Alerts', value: 0, icon: Shield, color: 'bg-red-500', change: '+0' }
          ].map((stat) => (
            <div key={stat.name} className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">{stat.name}</p>
                  <p className="text-3xl font-bold text-gray-900">{stat.value}</p>
                  <div className="flex items-center mt-1">
                    <TrendingUp className="h-4 w-4 text-green-500 mr-1" />
                    <span className="text-sm text-green-600">{stat.change}</span>
                  </div>
                </div>
                <div className={`${stat.color} p-3 rounded-full`}>
                  <stat.icon className="h-6 w-6 text-white" />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">
            {isSuperAdmin() ? 'Super Admin Dashboard' : 
             isAdmin() ? 'Admin Dashboard' : 
             'User Dashboard'}
          </h1>
          <p className="text-sm text-gray-600 mt-1">
            {isSuperAdmin() ? 'Full system access and control' :
             isAdmin() ? 'Administrative panel with management tools' :
             'Your personal dashboard'}
          </p>
        </div>
        <div className="flex items-center space-x-4">
          <div className="text-right">
            <div className="text-sm text-gray-500">
              Welcome back, {user?.name}
            </div>
            <div className="text-xs text-gray-400">
              {user?.role} • {user?.service_no}
            </div>
          </div>
          <button
            onClick={throttledRefresh}
            className="p-2 text-gray-500 hover:text-gray-700 transition-colors disabled:opacity-50"
            title="Refresh dashboard"
            disabled={dashboardLoading}
          >
            <RefreshCw className={`h-4 w-4 ${dashboardLoading ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>


      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {stats.map((stat) => (
          <div key={stat.name} className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">{stat.name}</p>
                <p className="text-3xl font-bold text-gray-900">{stat.value}</p>
                <p className="text-xs text-gray-500 mt-1">{stat.subtitle}</p>
                <div className="flex items-center mt-1">
                  <TrendingUp className="h-4 w-4 text-green-500 mr-1" />
                  <span className="text-sm text-green-600">{stat.change}</span>
                </div>
              </div>
              <div className={`${stat.color} p-3 rounded-full`}>
                <stat.icon className="h-6 w-6 text-white" />
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* User Statistics Pie Chart - Only for Admins and Super Admins */}
      {hasAnyPermission(['user.manage_roles', 'user.read']) && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-semibold text-gray-900">User Statistics Distribution</h2>
            <div className="flex items-center text-blue-600">
              <Users className="h-5 w-5 mr-2" />
              <span className="text-sm">Total Users: {dashboardStats?.userStats ? 
                (dashboardStats.userStats.super_admins + dashboardStats.userStats.admins + dashboardStats.userStats.regular_users) : 0
              }</span>
            </div>
          </div>
        
        <div className="flex flex-col lg:flex-row items-center gap-8">
          {/* Pie Chart */}
          <div className="relative w-64 h-64">
            <svg viewBox="0 0 100 100" className="w-full h-full transform -rotate-90">
              {/* Calculate percentages */}
              {(() => {
                const superAdmins = dashboardStats?.userStats?.super_admins || 0;
                const admins = dashboardStats?.userStats?.admins || 0;
                const regularUsers = dashboardStats?.userStats?.regular_users || 0;
                const total = superAdmins + admins + regularUsers;
                
                if (total === 0) {
                  return (
                    <circle
                      cx="50"
                      cy="50"
                      r="40"
                      fill="#f3f4f6"
                      stroke="#e5e7eb"
                      strokeWidth="2"
                    />
                  );
                }
                
                const superAdminPercent = (superAdmins / total) * 100;
                const adminPercent = (admins / total) * 100;
                const regularUserPercent = (regularUsers / total) * 100;
                
                let currentAngle = 0;
                
                return (
                  <>
                    {/* Super Admins */}
                    <path
                      d={`M 50 50 L ${50 + 40 * Math.cos(currentAngle * Math.PI / 180)} ${50 + 40 * Math.sin(currentAngle * Math.PI / 180)} A 40 40 0 ${superAdminPercent > 50 ? 1 : 0} 1 ${50 + 40 * Math.cos((currentAngle + superAdminPercent * 3.6) * Math.PI / 180)} ${50 + 40 * Math.sin((currentAngle + superAdminPercent * 3.6) * Math.PI / 180)} Z`}
                      fill="#3b82f6"
                      className="hover:opacity-80 transition-opacity"
                    />
                    {currentAngle += superAdminPercent * 3.6}
                    
                    {/* Admins */}
                    <path
                      d={`M 50 50 L ${50 + 40 * Math.cos(currentAngle * Math.PI / 180)} ${50 + 40 * Math.sin(currentAngle * Math.PI / 180)} A 40 40 0 ${adminPercent > 50 ? 1 : 0} 1 ${50 + 40 * Math.cos((currentAngle + adminPercent * 3.6) * Math.PI / 180)} ${50 + 40 * Math.sin((currentAngle + adminPercent * 3.6) * Math.PI / 180)} Z`}
                      fill="#10b981"
                      className="hover:opacity-80 transition-opacity"
                    />
                    {currentAngle += adminPercent * 3.6}
                    
                    {/* Regular Users */}
                    <path
                      d={`M 50 50 L ${50 + 40 * Math.cos(currentAngle * Math.PI / 180)} ${50 + 40 * Math.sin(currentAngle * Math.PI / 180)} A 40 40 0 ${regularUserPercent > 50 ? 1 : 0} 1 ${50 + 40 * Math.cos((currentAngle + regularUserPercent * 3.6) * Math.PI / 180)} ${50 + 40 * Math.sin((currentAngle + regularUserPercent * 3.6) * Math.PI / 180)} Z`}
                      fill="#f59e0b"
                      className="hover:opacity-80 transition-opacity"
                    />
                  </>
                );
              })()}
              
              {/* Center text */}
              <text
                x="50"
                y="50"
                textAnchor="middle"
                dominantBaseline="middle"
                className="fill-gray-700 text-xs font-medium transform rotate-90"
              >
                {dashboardStats?.userStats ? 
                  (dashboardStats.userStats.super_admins + dashboardStats.userStats.admins + dashboardStats.userStats.regular_users) : 0
                }
              </text>
              <text
                x="50"
                y="55"
                textAnchor="middle"
                dominantBaseline="middle"
                className="fill-gray-500 text-xs transform rotate-90"
              >
                Users
              </text>
            </svg>
          </div>
          
          {/* Legend */}
          <div className="flex-1 space-y-4">
            <div className="flex items-center space-x-3">
              <div className="w-4 h-4 bg-blue-500 rounded-full"></div>
              <div className="flex-1">
                <div className="flex justify-between items-center">
                  <span className="text-sm font-medium text-gray-900">Super Admins</span>
                  <span className="text-sm text-gray-500">{dashboardStats?.userStats?.super_admins || 0}</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2 mt-1">
                  <div 
                    className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                    style={{ 
                      width: dashboardStats?.userStats ? 
                        `${((dashboardStats.userStats.super_admins / (dashboardStats.userStats.super_admins + dashboardStats.userStats.admins + dashboardStats.userStats.regular_users)) * 100) || 0}%` 
                        : '0%' 
                    }}
                  ></div>
                </div>
              </div>
            </div>
            
            <div className="flex items-center space-x-3">
              <div className="w-4 h-4 bg-green-500 rounded-full"></div>
              <div className="flex-1">
                <div className="flex justify-between items-center">
                  <span className="text-sm font-medium text-gray-900">Admins</span>
                  <span className="text-sm text-gray-500">{dashboardStats?.userStats?.admins || 0}</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2 mt-1">
                  <div 
                    className="bg-green-500 h-2 rounded-full transition-all duration-300"
                    style={{ 
                      width: dashboardStats?.userStats ? 
                        `${((dashboardStats.userStats.admins / (dashboardStats.userStats.super_admins + dashboardStats.userStats.admins + dashboardStats.userStats.regular_users)) * 100) || 0}%` 
                        : '0%' 
                    }}
                  ></div>
                </div>
              </div>
            </div>
            
            <div className="flex items-center space-x-3">
              <div className="w-4 h-4 bg-yellow-500 rounded-full"></div>
              <div className="flex-1">
                <div className="flex justify-between items-center">
                  <span className="text-sm font-medium text-gray-900">Regular Users</span>
                  <span className="text-sm text-gray-500">{dashboardStats?.userStats?.regular_users || 0}</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2 mt-1">
                  <div 
                    className="bg-yellow-500 h-2 rounded-full transition-all duration-300"
                    style={{ 
                      width: dashboardStats?.userStats ? 
                        `${((dashboardStats.userStats.regular_users / (dashboardStats.userStats.super_admins + dashboardStats.userStats.admins + dashboardStats.userStats.regular_users)) * 100) || 0}%` 
                        : '0%' 
                    }}
                  ></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* User Statistics - Only for Admins and Super Admins */}
        {hasAnyPermission(['user.manage_roles', 'user.read']) && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-semibold text-gray-900">User Statistics</h2>
              <div className="flex items-center text-blue-600">
                <Users className="h-5 w-5 mr-2" />
                <span className="text-sm">Total Users</span>
              </div>
            </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-blue-700 font-medium">Super Admins</span>
                <span className="text-2xl font-bold text-blue-800">{dashboardStats?.userStats?.super_admins || 0}</span>
              </div>
            </div>
            <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-green-700 font-medium">Admins</span>
                <span className="text-2xl font-bold text-green-800">{dashboardStats?.userStats?.admins || 0}</span>
              </div>
            </div>
            <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-purple-700 font-medium">Navy Users</span>
                <span className="text-2xl font-bold text-purple-800">{dashboardStats?.userStats?.navy_users || 0}</span>
              </div>
            </div>
            <div className="bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-yellow-700 font-medium">New (30d)</span>
                <span className="text-2xl font-bold text-yellow-800">{dashboardStats?.userStats?.new_users_30d || 0}</span>
              </div>
            </div>
          </div>
          </div>
        )}

        {/* Security Alerts - Only for Admins and Super Admins */}
        {hasAnyPermission(['audit_log.read', 'security.view']) && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-gray-900">Security Overview</h2>
            <div className="flex items-center text-green-600">
              <Shield className="h-5 w-5 mr-2" />
              <span className="text-sm">All Clear</span>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="bg-gradient-to-br from-red-50 to-red-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-red-700 font-medium">Failed Logins (24h)</span>
                <span className="text-2xl font-bold text-red-800">{dashboardStats?.securityAlerts?.failed_logins_24h || 0}</span>
              </div>
            </div>
            <div className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-orange-700 font-medium">Password Changes (7d)</span>
                <span className="text-2xl font-bold text-orange-800">{dashboardStats?.securityAlerts?.password_changes_7d || 0}</span>
              </div>
            </div>
            <div className="bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-700 font-medium">Admin Actions (7d)</span>
                <span className="text-2xl font-bold text-gray-800">{dashboardStats?.securityAlerts?.admin_actions_7d || 0}</span>
              </div>
            </div>
            <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-blue-700 font-medium">Total Activities (24h)</span>
                <span className="text-2xl font-bold text-blue-800">{dashboardStats?.securityAlerts?.total_activities_24h || 0}</span>
              </div>
            </div>
          </div>
        </div>
        )}

        {/* Conversation Statistics - Available to all users */}
        {hasAnyPermission(['conversation.read', 'message.read']) && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-gray-900">Conversation Statistics</h2>
            <div className="flex items-center text-green-600">
              <MessageCircle className="h-5 w-5 mr-2" />
              <span className="text-sm">24h Activity</span>
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-green-700 font-medium">Active Conversations</span>
                <span className="text-2xl font-bold text-green-800">{dashboardStats?.conversationStats?.active_conversations_24h || 0}</span>
              </div>
            </div>
            <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-blue-700 font-medium">Unique Senders</span>
                <span className="text-2xl font-bold text-blue-800">{dashboardStats?.conversationStats?.unique_senders_24h || 0}</span>
              </div>
            </div>
          </div>
        </div>
        )}

        {/* Online Contact Status - Available to all users */}
        {hasAnyPermission(['user.read']) && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-gray-900">Online Contacts</h2>
            <div className="flex items-center text-green-600">
              <div className="w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"></div>
              <span className="text-sm">{dashboardStats?.onlineContacts?.online_now || 0} online</span>
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-green-700 font-medium">Online Now</span>
                <span className="text-2xl font-bold text-green-800">{dashboardStats?.onlineContacts?.online_now || 0}</span>
              </div>
            </div>
            <div className="bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-yellow-700 font-medium">Busy</span>
                <span className="text-2xl font-bold text-yellow-800">{dashboardStats?.onlineContacts?.busy_now || 0}</span>
              </div>
            </div>
            <div className="bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-700 font-medium">Offline</span>
                <span className="text-2xl font-bold text-gray-800">{dashboardStats?.onlineContacts?.offline_now || 0}</span>
              </div>
            </div>
          </div>
        </div>
        )}

        {/* Recent Activity - Only for Admins and Super Admins */}
        {hasAnyPermission(['audit_log.read']) && dashboardStats?.recentActivity && dashboardStats.recentActivity.length > 0 && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-gray-900">Recent Activity</h2>
            <div className="flex items-center text-blue-600">
              <Activity className="h-5 w-5 mr-2" />
              <span className="text-sm">Live Updates</span>
            </div>
          </div>
            <div className="space-y-3">
            {dashboardStats.recentActivity.slice(0, 10).map((activity, index) => (
              <div key={index} className="flex items-start space-x-3 p-4 hover:bg-gray-50 rounded-lg border border-gray-100 transition-colors">
                <div className="flex-shrink-0 w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                  <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                </div>
                  <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between">
                    <p className="text-sm font-semibold text-gray-900">{activity.action.replace('_', ' ')}</p>
                    <span className="text-xs text-gray-500">
                      {new Date(activity.created_at).toLocaleDateString()} {new Date(activity.created_at).toLocaleTimeString()}
                    </span>
                  </div>
                  <p className="text-sm text-gray-600 mt-1">{activity.details}</p>
                  <div className="flex items-center mt-2 text-xs text-gray-500">
                    <span className="bg-blue-100 text-blue-700 px-2 py-1 rounded-full font-medium">
                      {activity.user_rank} {activity.user_name}
                    </span>
                    <span className="ml-2">Target: {activity.target_name}</span>
                  </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

      {/* Analytics Charts - Only for Admins and Super Admins */}
      {hasAnyPermission(['dashboard.analytics', 'dashboard.view']) && analyticsData && (
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <h2 className="text-2xl font-bold text-gray-900 flex items-center">
              <BarChart3 className="h-6 w-6 mr-2" />
              Analytics
            </h2>
            <div className="flex items-center space-x-2">
              <span className="text-sm text-gray-500">
                Last {analyticsData?.period || 'N/A'}
              </span>
              <button
                onClick={fetchAnalytics}
                className="p-2 text-gray-500 hover:text-gray-700 transition-colors"
                title="Refresh analytics"
              >
                <RefreshCw className={`h-4 w-4 ${analyticsLoading ? 'animate-spin' : ''}`} />
              </button>
            </div>
          </div>
          
          {analyticsError ? (
            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
              <div className="flex items-center">
                <AlertCircle className="h-5 w-5 text-yellow-600 mr-2" />
                <div>
                  <h3 className="text-sm font-medium text-yellow-800">Analytics data unavailable</h3>
                  <p className="text-sm text-yellow-700 mt-1">{analyticsError}</p>
                </div>
                <button
                  onClick={fetchAnalytics}
                  className="ml-auto px-3 py-1 bg-yellow-100 text-yellow-800 rounded text-sm hover:bg-yellow-200 transition-colors"
                >
                  Retry
                </button>
              </div>
            </div>
          ) : (
            analyticsData && <AnalyticsCharts data={analyticsData} loading={analyticsLoading} />
          )}
        </div>
      )}

      {/* Quick Actions - Role-based */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-semibold text-gray-900">Quick Actions</h2>
          <div className="text-sm text-gray-500">
            Last updated: {dashboardStats?.timestamp ? new Date(dashboardStats.timestamp).toLocaleString() : 'Never'}
          </div>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {/* View Directory - Available to all users */}
          {hasAnyPermission(['user.read']) && (
            <button className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 hover:from-blue-100 hover:to-blue-200 rounded-lg transition-all duration-200 text-center group">
              <Users className="h-6 w-6 text-blue-600 mx-auto mb-2 group-hover:scale-110 transition-transform" />
              <span className="text-sm font-medium text-blue-900">View Directory</span>
            </button>
          )}
          
          {/* New Message - Available to all users */}
          {hasAnyPermission(['message.create', 'conversation.create']) && (
            <button className="p-4 bg-gradient-to-br from-green-50 to-green-100 hover:from-green-100 hover:to-green-200 rounded-lg transition-all duration-200 text-center group">
              <MessageCircle className="h-6 w-6 text-green-600 mx-auto mb-2 group-hover:scale-110 transition-transform" />
              <span className="text-sm font-medium text-green-900">New Message</span>
            </button>
          )}
          
          {/* Security Panel - Only for Admins and Super Admins */}
          {hasAnyPermission(['audit_log.read', 'security.view']) && (
            <button className="p-4 bg-gradient-to-br from-yellow-50 to-yellow-100 hover:from-yellow-100 hover:to-yellow-200 rounded-lg transition-all duration-200 text-center group">
              <Shield className="h-6 w-6 text-yellow-600 mx-auto mb-2 group-hover:scale-110 transition-transform" />
              <span className="text-sm font-medium text-yellow-900">Security Panel</span>
            </button>
          )}
          
          {/* Emergency - Available to all users */}
          <button className="p-4 bg-gradient-to-br from-red-50 to-red-100 hover:from-red-100 hover:to-red-200 rounded-lg transition-all duration-200 text-center group">
            <AlertTriangle className="h-6 w-6 text-red-600 mx-auto mb-2 group-hover:scale-110 transition-transform" />
            <span className="text-sm font-medium text-red-900">Emergency</span>
          </button>
          
          {/* User Management - Only for Super Admins */}
          {hasPermission('user.manage_roles') && (
            <button className="p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 hover:from-indigo-100 hover:to-indigo-200 rounded-lg transition-all duration-200 text-center group">
              <UserCheck className="h-6 w-6 text-indigo-600 mx-auto mb-2 group-hover:scale-110 transition-transform" />
              <span className="text-sm font-medium text-indigo-900">User Management</span>
            </button>
          )}
          
          {/* System Settings - Only for Super Admins */}
          {hasPermission('system_settings.read') && (
            <button className="p-4 bg-gradient-to-br from-gray-50 to-gray-100 hover:from-gray-100 hover:to-gray-200 rounded-lg transition-all duration-200 text-center group">
              <Settings className="h-6 w-6 text-gray-600 mx-auto mb-2 group-hover:scale-110 transition-transform" />
              <span className="text-sm font-medium text-gray-900">System Settings</span>
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
