import React, { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Users, 
  MessageCircle, 
  Shield, 
  Activity,
  TrendingUp,
  AlertTriangle,
  RefreshCw,
  AlertCircle,
  BarChart3,
  Settings,
  UserCheck,
  Eye,
  Clock,
  Database,
  FileText,
  Zap
} from 'lucide-react';
import { useApp } from '../context/AppContext';
import { useAuth } from '../context/AuthContext';
import AnalyticsCharts from '../components/AnalyticsCharts';

const Dashboard: React.FC = () => {
  const navigate = useNavigate();
  const { 
    dashboardStats, 
    dashboardLoading, 
    dashboardError, 
    fetchDashboardStats,
    analyticsData,
    analyticsLoading,
    analyticsError,
    fetchAnalytics
  } = useApp();
  const { user, isSuperAdmin, isAdmin, hasPermission, hasAnyPermission } = useAuth();
  
  // Check if user has dashboard access permission
  if (!hasAnyPermission(['dashboard.read', 'dashboard.view', 'admin.access', 'user.read'])) {
    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">Access Denied</h1>
            <p className="text-sm text-gray-600 mt-1">You don't have permission to access the dashboard</p>
          </div>
        </div>
        <div className="flex items-center justify-center h-64">
          <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
            <div className="text-red-600 mb-2">
              <Shield className="h-12 w-12 mx-auto" />
            </div>
            <h3 className="text-lg font-semibold text-red-800 mb-2">Dashboard Access Required</h3>
            <p className="text-sm text-red-700">
              You need dashboard permissions to view this page. Please contact your administrator.
            </p>
          </div>
        </div>
      </div>
    );
  }
  
  // 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]);

  // Dynamic Widget Configuration with Individual Permissions
  const getWidgetConfig = () => {
    return [
      {
        id: 'total_contacts',
        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`,
        permissions: ['dashboard.widget.contacts', 'contact.read', 'directory.access']
      },
      {
        id: 'active_conversations',
        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`,
        permissions: ['dashboard.widget.conversations', 'conversation.read', 'conversations.access']
      },
      {
        id: 'online_contacts',
        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`,
        permissions: ['dashboard.widget.online', 'user.read', 'contact.read']
      },
      {
        id: 'new_contacts_30d',
        name: 'New Contacts (30d)',
        value: dashboardStats?.totalContacts?.new_contacts_30d || 0,
        icon: Users,
        color: 'bg-orange-500',
        change: dashboardStats?.totalContacts?.new_contacts_30d ? `+${dashboardStats.totalContacts.new_contacts_30d}` : '+0',
        subtitle: 'Last 30 days new contacts',
        permissions: ['dashboard.widget.contacts', 'contact.read', 'directory.access']
      },
      {
        id: 'messages_today',
        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`,
        permissions: ['dashboard.widget.messages', 'message.read', 'conversation.read']
      },
      {
        id: 'security_alerts',
        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`,
        permissions: ['dashboard.widget.security', 'audit_log.read', 'security.view']
      },
      {
        id: 'user_management',
        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 contacts`,
        permissions: ['user.manage_roles', 'user.read', 'admin.access']
      },
      {
        id: 'admin_users',
        name: 'Admin Users',
        value: dashboardStats?.users?.admin_users || 0,
        icon: Shield,
        color: 'bg-purple-500',
        change: '',
        subtitle: '',
        permissions: ['dashboard.view']
      },
      {
        id: 'view_users',
        name: 'View Users',
        value: dashboardStats?.users?.view_users || 0,
        icon: Eye,
        color: 'bg-green-500',
        change: '',
        subtitle: '',
        permissions: ['dashboard.view']
      },
      {
        id: 'system_status',
        name: 'System Status',
        value: dashboardStats?.systemStatus?.uptime_percentage || 99,
        icon: Database,
        color: 'bg-emerald-500',
        change: dashboardStats?.systemStatus?.response_time ? `${dashboardStats.systemStatus.response_time}ms` : '50ms',
        subtitle: `${dashboardStats?.systemStatus?.active_services || 8} services running`,
        permissions: ['dashboard.widget.system', 'system_settings.read', 'admin.access']
      },
      {
        id: 'recent_activity',
        name: 'Recent Activity',
        value: dashboardStats?.recentActivity?.length || 0,
        icon: Clock,
        color: 'bg-orange-500',
        change: dashboardStats?.recentActivity?.length ? `${dashboardStats.recentActivity.length} events` : '0 events',
        subtitle: 'Last 24 hours activity',
        permissions: ['audit_log.read', 'dashboard.widget.activity']
      }
    ];
  };

  // Filter widgets based on user permissions only
  const getVisibleWidgets = () => {
    const allWidgets = getWidgetConfig();
    
    return allWidgets.filter(widget => {
      // Check if user has any of the required permissions
      return hasAnyPermission(widget.permissions);
    });
  };

  const visibleWidgets = getVisibleWidgets();

  // 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">
          {visibleWidgets.slice(0, 4).map((widget) => (
            <div key={widget.id} 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">{widget.name}</p>
                  <p className="text-3xl font-bold text-gray-900">0</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">+0</span>
                  </div>
                </div>
                <div className={`${widget.color} p-3 rounded-full`}>
                  <widget.icon className="h-6 w-6 text-white" />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <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>

      {/* Dynamic Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {visibleWidgets.map((widget) => (
          <div key={widget.id} className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-shadow">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">{widget.name}</p>
                <p className="text-3xl font-bold text-gray-900">{widget.value}</p>
                <p className="text-xs text-gray-500 mt-1">{widget.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">{widget.change}</span>
                </div>
              </div>
              <div className={`${widget.color} p-3 rounded-full`}>
                <widget.icon className="h-6 w-6 text-white" />
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Detailed Sections Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        
        {/* User Statistics Pie Chart - Permission Based */}
        {hasAnyPermission(['dashboard.chart']) && (
          <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>
        )}

        {/* Security Alerts - Permission Based */}
        {hasAnyPermission(['dashboard.widget.security']) && (
          <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>
        )}

        {/* User Statistics - Permission Based */}
        {hasAnyPermission(['dashboard.users']) && (
          <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>
        )}

        {/* Conversation Statistics - Permission Based */}
        {hasAnyPermission(['conversation.read', 'message.read', 'conversations.access']) && (
          <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 - Permission Based */}
        {hasAnyPermission(['dashboard.widget.online']) && (
          <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 - Permission Based */}
        {hasAnyPermission(['dashboard.widget.activity']) && 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>
        )}
      </div>

      {/* Analytics Charts - Permission Based */}
      {hasAnyPermission(['dashboard.analytics']) && 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 - Dynamic Permission */}
      <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 - Permission Based */}
          {hasAnyPermission(['directory.access']) && (
            <button 
              onClick={() => navigate('/directory')}
              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 cursor-pointer"
            >
              <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 - Permission Based */}
          {hasAnyPermission(['conversations.access']) && (
            <button 
              onClick={() => navigate('/conversations')}
              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 cursor-pointer"
            >
              <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 - Permission Based */}
          {hasAnyPermission(['dashboard.widget.security']) && (
            <button 
              onClick={() => navigate('/settings')}
              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 cursor-pointer"
            >
              <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 */}
          {hasAnyPermission(['dashboard.widget.security']) && (
          <button 
            onClick={() => navigate('/emergency')}
            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 cursor-pointer"
          >
            <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 - Permission Based */}
          {hasAnyPermission(['user.manage_roles', 'admin.access']) && (
            <button 
              onClick={() => navigate('/settings')}
              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 cursor-pointer"
            >
              <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 - Permission Based */}
          {hasAnyPermission(['system_settings.read', 'admin.access']) && (
            <button 
              onClick={() => navigate('/settings')}
              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 cursor-pointer"
            >
              <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>
          )}

          {/* Analytics - Permission Based */}
          {hasAnyPermission(['dashboard.analytics']) && (
            <button 
              onClick={() => navigate('/analytics')}
              className="p-4 bg-gradient-to-br from-purple-50 to-purple-100 hover:from-purple-100 hover:to-purple-200 rounded-lg transition-all duration-200 text-center group cursor-pointer"
            >
              <BarChart3 className="h-6 w-6 text-purple-600 mx-auto mb-2 group-hover:scale-110 transition-transform" />
              <span className="text-sm font-medium text-purple-900">Analytics</span>
            </button>
          )}

          {/* Reports - Permission Based */}
          {hasAnyPermission(['dashboard.reports']) && (
            <button 
              onClick={() => navigate('/reports')}
              className="p-4 bg-gradient-to-br from-emerald-50 to-emerald-100 hover:from-emerald-100 hover:to-emerald-200 rounded-lg transition-all duration-200 text-center group cursor-pointer"
            >
              <FileText className="h-6 w-6 text-emerald-600 mx-auto mb-2 group-hover:scale-110 transition-transform" />
              <span className="text-sm font-medium text-emerald-900">Reports</span>
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
