'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import {
  Users,
  FileText,
  Calendar,
  Newspaper,
  TrendingUp,
  Clock,
  CheckCircle,
  AlertCircle,
  XCircle,
  Briefcase,
  UserPlus,
  Bell,
  Menu,
  Building2,
  Shield,
  BarChart3,
  Activity,
} from 'lucide-react'
import { isAuthenticated, getAdminUser } from '@/lib/auth'
import { apiGet } from '@/lib/apiClient'
import LoadingSpinner from '@/components/LoadingSpinner'

interface StatCard {
  title: string
  value: string | number
  icon: React.ComponentType<{ className?: string }>
  color: string
  change?: string
}

interface RecentActivity {
  id: string
  type: 'create' | 'update' | 'delete' | 'publish'
  message: string
  time: string
  user: string
  timestamp: Date
}

interface DashboardStats {
  totalUsers: number
  totalArticles: number
  totalEvents: number
  totalPages: number
  totalTenders: number
  totalVacancies: number
  totalNewsTickers: number
  totalMenuItems: number
  totalDepartments: number
  totalRoles: number
  publishedArticles: number
  draftArticles: number
  publishedEvents: number
  draftEvents: number
  publishedPages: number
  draftPages: number
  openTenders: number
  closedTenders: number
  awardedTenders: number
  draftTenders: number
  openVacancies: number
  closedVacancies: number
  filledVacancies: number
  draftVacancies: number
  activeNewsTickers: number
  inactiveNewsTickers: number
  upcomingTenders: number
  upcomingVacancies: number
}

export default function AdminDashboard() {
  const router = useRouter()
  const [user, setUser] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [stats, setStats] = useState<DashboardStats>({
    totalUsers: 0,
    totalArticles: 0,
    totalEvents: 0,
    totalPages: 0,
    totalTenders: 0,
    totalVacancies: 0,
    totalNewsTickers: 0,
    totalMenuItems: 0,
    totalDepartments: 0,
    totalRoles: 0,
    publishedArticles: 0,
    draftArticles: 0,
    publishedEvents: 0,
    draftEvents: 0,
    publishedPages: 0,
    draftPages: 0,
    openTenders: 0,
    closedTenders: 0,
    awardedTenders: 0,
    draftTenders: 0,
    openVacancies: 0,
    closedVacancies: 0,
    filledVacancies: 0,
    draftVacancies: 0,
    activeNewsTickers: 0,
    inactiveNewsTickers: 0,
    upcomingTenders: 0,
    upcomingVacancies: 0,
  })
  const [recentActivities, setRecentActivities] = useState<RecentActivity[]>([])
  const [recentTenders, setRecentTenders] = useState<any[]>([])
  const [recentVacancies, setRecentVacancies] = useState<any[]>([])

  useEffect(() => {
      if (!isAuthenticated()) {
        router.push('/admin')
        return
      }

      const userData = getAdminUser()
      if (userData) {
        setUser(userData)
      }

    fetchDashboardData()
  }, [router])

  const fetchDashboardData = async () => {
    try {
      // Fetch all data in parallel
      const [
        usersResult,
        articlesResult,
        eventsResult,
        pagesResult,
        tendersResult,
        vacanciesResult,
        newsTickerResult,
        menuResult,
        departmentsResult,
        rolesResult,
      ] = await Promise.all([
        apiGet<any[]>('/users').catch(() => ({ success: false, data: [] })),
        apiGet<any[]>('/news-articles/all').catch(() => ({ success: false, data: [] })),
        apiGet<any[]>('/events/all').catch(() => ({ success: false, data: [] })),
        apiGet<any[]>('/pages').catch(() => ({ success: false, data: [] })),
        apiGet<any[]>('/tenders/all?limit=1000').catch((err) => {
          console.error('Error fetching tenders:', err)
          return { success: false, data: [] }
        }),
        apiGet<any[]>('/vacancies/all?limit=1000').catch((err) => {
          console.error('Error fetching vacancies:', err)
          return { success: false, data: [] }
        }),
        apiGet<any[]>('/news-ticker/all').catch(() => ({ success: false, data: [] })),
        apiGet<any[]>('/menu/all').catch(() => ({ success: false, data: [] })),
        apiGet<any[]>('/departments').catch(() => ({ success: false, data: [] })),
        apiGet<any[]>('/roles').catch(() => ({ success: false, data: [] })),
      ])

      // Process users
      const users = usersResult.success ? usersResult.data || [] : []
      const totalUsers = users.length

      // Process articles
      const articles = articlesResult.success ? articlesResult.data || [] : []
      const totalArticles = articles.length
      const publishedArticles = articles.filter((a: any) => a.isPublished).length
      const draftArticles = articles.filter((a: any) => !a.isPublished).length

      // Process events
      const events = eventsResult.success ? eventsResult.data || [] : []
      const totalEvents = events.length
      const publishedEvents = events.filter((e: any) => e.isPublished).length
      const draftEvents = events.filter((e: any) => !e.isPublished).length

      // Process pages
      const pages = pagesResult.success ? pagesResult.data || [] : []
      // Handle case where API returns array directly
      const pagesArray = Array.isArray(pages) ? pages : []
      const totalPages = pagesArray.length
      const publishedPages = pagesArray.filter((p: any) => p.isPublished !== false).length
      const draftPages = pagesArray.filter((p: any) => p.isPublished === false).length

      // Process tenders
      const tenders = tendersResult.success ? (tendersResult.data || []) : []
      if (!tendersResult.success) {
        console.error('Failed to fetch tenders:', tendersResult)
      }
      const totalTenders = Array.isArray(tenders) ? tenders.length : 0
      const openTenders = tenders.filter((t: any) => {
        const status = (t.status || '').toLowerCase()
        return status === 'open'
      }).length
      const closedTenders = tenders.filter((t: any) => {
        const status = (t.status || '').toLowerCase()
        return status === 'closed'
      }).length
      const awardedTenders = tenders.filter((t: any) => {
        const status = (t.status || '').toLowerCase()
        return status === 'awarded'
      }).length
      const draftTenders = tenders.filter((t: any) => {
        const status = (t.status || '').toLowerCase()
        return status === 'draft'
      }).length
      const now = new Date()
      const upcomingTenders = tenders.filter((t: any) => {
        const status = (t.status || '').toLowerCase()
        if (status === 'open' && t.closingDate) {
          const closingDate = new Date(t.closingDate)
          return closingDate > now && closingDate <= new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000) // Next 30 days
        }
        return false
      }).length

      // Process vacancies
      const vacancies = vacanciesResult.success ? (vacanciesResult.data || []) : []
      if (!vacanciesResult.success) {
        console.error('Failed to fetch vacancies:', vacanciesResult)
      }
      const totalVacancies = Array.isArray(vacancies) ? vacancies.length : 0
      const openVacancies = vacancies.filter((v: any) => {
        const status = (v.status || '').toLowerCase()
        return status === 'open'
      }).length
      const closedVacancies = vacancies.filter((v: any) => {
        const status = (v.status || '').toLowerCase()
        return status === 'closed'
      }).length
      const filledVacancies = vacancies.filter((v: any) => {
        const status = (v.status || '').toLowerCase()
        return status === 'filled'
      }).length
      const draftVacancies = vacancies.filter((v: any) => {
        const status = (v.status || '').toLowerCase()
        return status === 'draft'
      }).length
      const upcomingVacancies = vacancies.filter((v: any) => {
        const status = (v.status || '').toLowerCase()
        if (status === 'open' && v.closingDate) {
          const closingDate = new Date(v.closingDate)
          return closingDate > now && closingDate <= new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000) // Next 30 days
        }
        return false
      }).length

      // Process news ticker
      const newsTickers = newsTickerResult.success ? newsTickerResult.data || [] : []
      const totalNewsTickers = newsTickers.length
      const activeNewsTickers = newsTickers.filter((nt: any) => nt.isActive).length
      const inactiveNewsTickers = newsTickers.filter((nt: any) => !nt.isActive).length

      // Process menu items
      const menuItems = menuResult.success ? menuResult.data || [] : []
      // Menu items might be hierarchical, so we need to count all items recursively
      const countMenuItems = (items: any[]): number => {
        let count = items.length
        items.forEach((item: any) => {
          if (item.children && Array.isArray(item.children)) {
            count += countMenuItems(item.children)
          }
        })
        return count
      }
      const totalMenuItems = Array.isArray(menuItems) ? countMenuItems(menuItems) : 0

      // Process departments
      const departments = departmentsResult.success ? departmentsResult.data || [] : []
      const totalDepartments = Array.isArray(departments) ? departments.length : 0

      // Process roles
      const roles = rolesResult.success ? rolesResult.data || [] : []
      const totalRoles = Array.isArray(roles) ? roles.length : 0

      setStats({
        totalUsers,
        totalArticles,
        totalEvents,
        totalPages,
        totalTenders,
        totalVacancies,
        totalNewsTickers,
        totalMenuItems,
        totalDepartments,
        totalRoles,
        publishedArticles,
        draftArticles,
        publishedEvents,
        draftEvents,
        publishedPages,
        draftPages,
        openTenders,
        closedTenders,
        awardedTenders,
        draftTenders,
        openVacancies,
        closedVacancies,
        filledVacancies,
        draftVacancies,
        activeNewsTickers,
        inactiveNewsTickers,
        upcomingTenders,
        upcomingVacancies,
      })

      // Build recent activities from all sources
      const activities: RecentActivity[] = []

      // Recent articles
      articles
        .sort((a: any, b: any) => new Date(b.updatedAt || b.createdAt).getTime() - new Date(a.updatedAt || a.createdAt).getTime())
        .slice(0, 2)
        .forEach((article: any) => {
          const date = new Date(article.updatedAt || article.createdAt)
          activities.push({
            id: article._id,
            type: article.isPublished ? 'publish' : 'create',
            message: article.isPublished 
              ? `Article published: "${article.title}"`
              : `Article created: "${article.title}"`,
            time: formatTimeAgo(date),
            user: article.createdBy?.firstName 
              ? `${article.createdBy.firstName} ${article.createdBy.lastName || ''}`.trim()
              : 'System',
            timestamp: date,
          })
        })

      // Recent events
      events
        .sort((a: any, b: any) => new Date(b.updatedAt || b.createdAt).getTime() - new Date(a.updatedAt || a.createdAt).getTime())
        .slice(0, 1)
        .forEach((event: any) => {
          const date = new Date(event.updatedAt || event.createdAt)
          activities.push({
            id: event._id,
            type: event.isPublished ? 'publish' : 'create',
            message: event.isPublished
              ? `Event published: "${event.title}"`
              : `Event created: "${event.title}"`,
            time: formatTimeAgo(date),
            user: event.createdBy?.firstName
              ? `${event.createdBy.firstName} ${event.createdBy.lastName || ''}`.trim()
              : 'System',
            timestamp: date,
          })
        })

      // Recent tenders
      tenders
        .sort((a: any, b: any) => new Date(b.updatedAt || b.createdAt).getTime() - new Date(a.updatedAt || a.createdAt).getTime())
        .slice(0, 1)
        .forEach((tender: any) => {
          const date = new Date(tender.updatedAt || tender.createdAt)
          activities.push({
            id: tender._id,
            type: tender.status === 'open' ? 'publish' : 'create',
            message: `Tender ${tender.status}: "${tender.title}"`,
            time: formatTimeAgo(date),
            user: tender.createdBy?.firstName
              ? `${tender.createdBy.firstName} ${tender.createdBy.lastName || ''}`.trim()
              : 'System',
            timestamp: date,
          })
        })

      // Recent vacancies
      vacancies
        .sort((a: any, b: any) => new Date(b.updatedAt || b.createdAt).getTime() - new Date(a.updatedAt || a.createdAt).getTime())
        .slice(0, 1)
        .forEach((vacancy: any) => {
          const date = new Date(vacancy.updatedAt || vacancy.createdAt)
          activities.push({
            id: vacancy._id,
            type: vacancy.status === 'open' ? 'publish' : 'create',
            message: `Vacancy ${vacancy.status}: "${vacancy.title}"`,
            time: formatTimeAgo(date),
            user: vacancy.createdBy?.firstName
              ? `${vacancy.createdBy.firstName} ${vacancy.createdBy.lastName || ''}`.trim()
              : 'System',
            timestamp: date,
          })
        })

      // Recent users
      users
        .sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
        .slice(0, 1)
        .forEach((user: any) => {
          const date = new Date(user.createdAt)
          activities.push({
            id: user._id,
            type: 'create',
            message: `New user registered: ${user.firstName} ${user.lastName}`,
            time: formatTimeAgo(date),
            user: 'System',
            timestamp: date,
          })
        })

      // Sort all activities by timestamp and take most recent 8
      activities.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
      setRecentActivities(activities.slice(0, 8))

      // Set recent tenders (most recent 5)
      const sortedTenders = tenders
        .sort((a: any, b: any) => new Date(b.updatedAt || b.createdAt).getTime() - new Date(a.updatedAt || a.createdAt).getTime())
        .slice(0, 5)
      setRecentTenders(sortedTenders)

      // Set recent vacancies (most recent 5)
      const sortedVacancies = vacancies
        .sort((a: any, b: any) => new Date(b.updatedAt || b.createdAt).getTime() - new Date(a.updatedAt || a.createdAt).getTime())
        .slice(0, 5)
      setRecentVacancies(sortedVacancies)

    } catch (error: any) {
      console.error('Error fetching dashboard data:', error)
    } finally {
      setLoading(false)
    }
  }

  const formatTimeAgo = (date: Date): string => {
    const now = new Date()
    const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000)

    if (diffInSeconds < 60) return 'just now'
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`
    if (diffInSeconds < 604800) return `${Math.floor(diffInSeconds / 86400)} days ago`
    return date.toLocaleDateString()
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <LoadingSpinner />
      </div>
    )
  }

  const statCards: StatCard[] = [
    {
      title: 'Total Users',
      value: stats.totalUsers,
      icon: Users,
      color: 'from-blue-500 to-blue-600',
    },
    {
      title: 'News Articles',
      value: stats.totalArticles,
      icon: Newspaper,
      color: 'from-green-500 to-green-600',
    },
    {
      title: 'Events',
      value: stats.totalEvents,
      icon: Calendar,
      color: 'from-purple-500 to-purple-600',
    },
    {
      title: 'Pages',
      value: stats.totalPages,
      icon: FileText,
      color: 'from-orange-500 to-orange-600',
    },
    {
      title: 'Tenders',
      value: stats.totalTenders,
      icon: Briefcase,
      color: 'from-cyan-500 to-cyan-600',
    },
    {
      title: 'Vacancies',
      value: stats.totalVacancies,
      icon: UserPlus,
      color: 'from-pink-500 to-pink-600',
    },
    {
      title: 'News Ticker',
      value: stats.totalNewsTickers,
      icon: Bell,
      color: 'from-yellow-500 to-yellow-600',
    },
    {
      title: 'Menu Items',
      value: stats.totalMenuItems,
      icon: Menu,
      color: 'from-indigo-500 to-indigo-600',
    },
  ]

  const getRoleDisplayName = (role: string) => {
    const roleMap: { [key: string]: string } = {
      'ADMINISTRATOR': 'System Administrator',
      'COMMUNICATIONS_MANAGER': 'Communications Manager',
      'SENIOR_COMMUNICATIONS_OFFICER': 'Senior Communications Officer',
      'COMMUNICATIONS_OFFICER': 'Communications Officer',
      'SOCIAL_MEDIA_OFFICER': 'Social Media Officer',
      'CONTENT_WRITER': 'Content Writer',
      'GRAPHIC_DESIGNER': 'Graphic Designer',
      'JUNIOR_COMMUNICATIONS_OFFICER': 'Junior Communications Officer',
      'COMMUNICATIONS_INTERN': 'Communications Intern',
    }
    return roleMap[role] || role
  }

  const getActivityIcon = (type: string) => {
    switch (type) {
      case 'create':
      case 'publish':
        return <CheckCircle className="w-4 h-4 text-green-400" />
      case 'update':
        return <AlertCircle className="w-4 h-4 text-blue-400" />
      case 'delete':
        return <XCircle className="w-4 h-4 text-red-400" />
      default:
        return <AlertCircle className="w-4 h-4 text-yellow-400" />
    }
  }

  const getActivityBgColor = (type: string) => {
    switch (type) {
      case 'create':
      case 'publish':
        return 'bg-green-500/20'
      case 'update':
        return 'bg-blue-500/20'
      case 'delete':
        return 'bg-red-500/20'
      default:
        return 'bg-yellow-500/20'
    }
  }

  return (
    <div className="space-y-6">
      {/* Welcome Section */}
      <div className="bg-gradient-to-r from-primary to-secondary rounded-2xl p-6 text-white">
        <h1 className="text-3xl font-bold mb-2">
          Welcome back, {user?.firstName || 'Admin'}! 👋
        </h1>
        <p className="text-white/90">
          {getRoleDisplayName(user?.role || 'ADMINISTRATOR')} • Madibeng Communications Unit
        </p>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {statCards.map((stat, index) => {
          const Icon = stat.icon
          return (
            <div
              key={index}
              className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20 hover:border-white/40 transition-all hover:scale-105"
            >
              <div className="flex items-center justify-between mb-4">
                <div className={`p-3 bg-gradient-to-br ${stat.color} rounded-lg`}>
                  <Icon className="w-6 h-6 text-white" />
                </div>
              </div>
              <h3 className="text-white/70 text-sm mb-1">{stat.title}</h3>
              <p className="text-3xl font-bold text-white">{stat.value}</p>
            </div>
          )
        })}
      </div>

      {/* Module Insights Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {/* Tenders Status */}
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-bold text-white flex items-center gap-2">
              <Briefcase className="w-5 h-5" />
              Tenders
            </h3>
            <BarChart3 className="w-5 h-5 text-white/50" />
          </div>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Open</span>
              <span className="text-green-400 font-bold">{stats.openTenders}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Closed</span>
              <span className="text-red-400 font-bold">{stats.closedTenders}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Awarded</span>
              <span className="text-blue-400 font-bold">{stats.awardedTenders}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Draft</span>
              <span className="text-gray-400 font-bold">{stats.draftTenders}</span>
            </div>
            <div className="flex justify-between items-center pt-2 border-t border-white/10">
              <span className="text-white/70 text-sm">Closing Soon</span>
              <span className="text-yellow-400 font-bold">{stats.upcomingTenders}</span>
            </div>
          </div>
        </div>

        {/* Vacancies Status */}
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-bold text-white flex items-center gap-2">
              <UserPlus className="w-5 h-5" />
              Vacancies
            </h3>
            <BarChart3 className="w-5 h-5 text-white/50" />
          </div>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Open</span>
              <span className="text-green-400 font-bold">{stats.openVacancies}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Closed</span>
              <span className="text-red-400 font-bold">{stats.closedVacancies}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Filled</span>
              <span className="text-blue-400 font-bold">{stats.filledVacancies}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Draft</span>
              <span className="text-gray-400 font-bold">{stats.draftVacancies}</span>
            </div>
            <div className="flex justify-between items-center pt-2 border-t border-white/10">
              <span className="text-white/70 text-sm">Closing Soon</span>
              <span className="text-yellow-400 font-bold">{stats.upcomingVacancies}</span>
            </div>
          </div>
        </div>

        {/* System Overview */}
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-bold text-white flex items-center gap-2">
              <Activity className="w-5 h-5" />
              System
            </h3>
            <Shield className="w-5 h-5 text-white/50" />
          </div>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Departments</span>
              <span className="text-white font-bold">{stats.totalDepartments}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Roles</span>
              <span className="text-white font-bold">{stats.totalRoles}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-white/70 text-sm">Active Tickers</span>
              <span className="text-green-400 font-bold">{stats.activeNewsTickers}</span>
            </div>
            <div className="flex justify-between items-center pt-2 border-t border-white/10">
              <span className="text-white/70 text-sm">Inactive Tickers</span>
              <span className="text-red-400 font-bold">{stats.inactiveNewsTickers}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Recent Tenders and Vacancies */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Tenders */}
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-bold text-white flex items-center gap-2">
              <Briefcase className="w-5 h-5" />
              Recent Tenders
            </h2>
            <button
              onClick={() => router.push('/admin/tenders')}
              className="text-sm text-primary hover:text-primary-dark transition-colors"
            >
              View All →
            </button>
          </div>
          <div className="space-y-3 max-h-[400px] overflow-y-auto">
            {recentTenders.length > 0 ? (
              recentTenders.map((tender: any) => {
                const closingDate = tender.closingDate ? new Date(tender.closingDate) : null
                const isUpcoming = closingDate && closingDate > new Date() && closingDate <= new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
                const statusColor = tender.status === 'open' 
                  ? 'bg-green-500/20 text-green-400'
                  : tender.status === 'closed'
                  ? 'bg-red-500/20 text-red-400'
                  : tender.status === 'awarded'
                  ? 'bg-blue-500/20 text-blue-400'
                  : 'bg-gray-500/20 text-gray-400'
                
                return (
                  <div
                    key={tender._id}
                    onClick={() => router.push(`/admin/tenders/${tender._id}`)}
                    className="p-4 bg-white/5 rounded-lg hover:bg-white/10 transition-all cursor-pointer border border-white/10"
                  >
                    <div className="flex items-start justify-between mb-2">
                      <h3 className="text-white font-medium text-sm flex-1 line-clamp-2">
                        {tender.title}
                      </h3>
                      <span className={`px-2 py-1 text-xs font-medium rounded ml-2 ${statusColor}`}>
                        {tender.status}
                      </span>
                    </div>
                    {tender.category && (
                      <p className="text-white/50 text-xs mb-2">{tender.category}</p>
                    )}
                    {closingDate && (
                      <div className="flex items-center gap-2 text-xs">
                        <Clock className="w-3 h-3 text-white/50" />
                        <span className={isUpcoming ? 'text-yellow-400' : 'text-white/50'}>
                          Closes: {closingDate.toLocaleDateString()}
                        </span>
                        {isUpcoming && (
                          <span className="px-2 py-0.5 bg-yellow-500/20 text-yellow-400 rounded text-xs">
                            Soon
                          </span>
                        )}
                      </div>
                    )}
                  </div>
                )
              })
            ) : (
              <div className="text-center py-8 text-white/50">
                <Briefcase className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>No tenders yet</p>
                <button
                  onClick={() => router.push('/admin/tenders/new')}
                  className="mt-2 text-primary hover:text-primary-dark text-sm"
                >
                  Create your first tender
                </button>
              </div>
            )}
          </div>
        </div>

        {/* Recent Vacancies */}
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-bold text-white flex items-center gap-2">
              <UserPlus className="w-5 h-5" />
              Recent Vacancies
            </h2>
            <button
              onClick={() => router.push('/admin/vacancies')}
              className="text-sm text-primary hover:text-primary-dark transition-colors"
            >
              View All →
            </button>
          </div>
          <div className="space-y-3 max-h-[400px] overflow-y-auto">
            {recentVacancies.length > 0 ? (
              recentVacancies.map((vacancy: any) => {
                const closingDate = vacancy.closingDate ? new Date(vacancy.closingDate) : null
                const isUpcoming = closingDate && closingDate > new Date() && closingDate <= new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
                const statusColor = vacancy.status === 'open' 
                  ? 'bg-green-500/20 text-green-400'
                  : vacancy.status === 'closed'
                  ? 'bg-red-500/20 text-red-400'
                  : vacancy.status === 'filled'
                  ? 'bg-blue-500/20 text-blue-400'
                  : 'bg-gray-500/20 text-gray-400'
                
                return (
                  <div
                    key={vacancy._id}
                    onClick={() => router.push(`/admin/vacancies/${vacancy._id}`)}
                    className="p-4 bg-white/5 rounded-lg hover:bg-white/10 transition-all cursor-pointer border border-white/10"
                  >
                    <div className="flex items-start justify-between mb-2">
                      <h3 className="text-white font-medium text-sm flex-1 line-clamp-2">
                        {vacancy.title}
                      </h3>
                      <span className={`px-2 py-1 text-xs font-medium rounded ml-2 ${statusColor}`}>
                        {vacancy.status}
                      </span>
                    </div>
                    {vacancy.department && (
                      <p className="text-white/50 text-xs mb-2">{vacancy.department}</p>
                    )}
                    {vacancy.positionType && (
                      <p className="text-white/50 text-xs mb-2">{vacancy.positionType}</p>
                    )}
                    {closingDate && (
                      <div className="flex items-center gap-2 text-xs">
                        <Clock className="w-3 h-3 text-white/50" />
                        <span className={isUpcoming ? 'text-yellow-400' : 'text-white/50'}>
                          Closes: {closingDate.toLocaleDateString()}
                        </span>
                        {isUpcoming && (
                          <span className="px-2 py-0.5 bg-yellow-500/20 text-yellow-400 rounded text-xs">
                            Soon
                          </span>
                        )}
                      </div>
                    )}
                  </div>
                )
              })
            ) : (
              <div className="text-center py-8 text-white/50">
                <UserPlus className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>No vacancies yet</p>
                <button
                  onClick={() => router.push('/admin/vacancies/new')}
                  className="mt-2 text-primary hover:text-primary-dark text-sm"
                >
                  Create your first vacancy
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Activity */}
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-bold text-white">Recent Activity</h2>
            <Clock className="w-5 h-5 text-white/50" />
          </div>
          <div className="space-y-4 max-h-[500px] overflow-y-auto">
            {recentActivities.length > 0 ? (
              recentActivities.map((activity) => (
              <div
                key={activity.id}
                className="flex items-start gap-3 p-3 bg-white/5 rounded-lg hover:bg-white/10 transition-all"
              >
                  <div className={`p-2 rounded-lg ${getActivityBgColor(activity.type)}`}>
                    {getActivityIcon(activity.type)}
                </div>
                <div className="flex-1">
                  <p className="text-white text-sm">{activity.message}</p>
                  <p className="text-white/50 text-xs mt-1">
                    {activity.user} • {activity.time}
                  </p>
                </div>
              </div>
              ))
            ) : (
              <div className="text-center py-8 text-white/50">
                <p>No recent activity</p>
              </div>
            )}
          </div>
        </div>

        {/* Quick Actions */}
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
          <h2 className="text-xl font-bold text-white mb-6">Quick Actions</h2>
          <div className="grid grid-cols-2 gap-4">
            <button
              onClick={() => router.push('/admin/news-articles/new')}
              className="p-4 bg-gradient-to-br from-green-500 to-green-600 rounded-lg text-white text-left hover:scale-105 transition-all"
            >
              <Newspaper className="w-6 h-6 mb-2" />
              <p className="font-medium">New Article</p>
            </button>
            <button
              onClick={() => router.push('/admin/events/new')}
              className="p-4 bg-gradient-to-br from-purple-500 to-purple-600 rounded-lg text-white text-left hover:scale-105 transition-all"
            >
              <Calendar className="w-6 h-6 mb-2" />
              <p className="font-medium">New Event</p>
            </button>
            <button
              onClick={() => router.push('/admin/pages/new')}
              className="p-4 bg-gradient-to-br from-orange-500 to-orange-600 rounded-lg text-white text-left hover:scale-105 transition-all"
            >
              <FileText className="w-6 h-6 mb-2" />
              <p className="font-medium">New Page</p>
            </button>
            <button
              onClick={() => router.push('/admin/users/new')}
              className="p-4 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg text-white text-left hover:scale-105 transition-all"
            >
              <Users className="w-6 h-6 mb-2" />
              <p className="font-medium">New User</p>
            </button>
            <button
              onClick={() => router.push('/admin/tenders/new')}
              className="p-4 bg-gradient-to-br from-cyan-500 to-cyan-600 rounded-lg text-white text-left hover:scale-105 transition-all"
            >
              <Briefcase className="w-6 h-6 mb-2" />
              <p className="font-medium">New Tender</p>
            </button>
            <button
              onClick={() => router.push('/admin/vacancies/new')}
              className="p-4 bg-gradient-to-br from-pink-500 to-pink-600 rounded-lg text-white text-left hover:scale-105 transition-all"
            >
              <UserPlus className="w-6 h-6 mb-2" />
              <p className="font-medium">New Vacancy</p>
            </button>
          </div>
        </div>
      </div>

      {/* Content Status */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
        <h2 className="text-xl font-bold text-white mb-6">Content Status</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="text-center">
            <div className="text-3xl font-bold text-yellow-400 mb-2">
              {stats.draftArticles + stats.draftEvents + stats.draftPages}
          </div>
            <p className="text-white/70">In Draft</p>
            <div className="text-white/50 text-xs mt-1">
              {stats.draftArticles} articles, {stats.draftEvents} events, {stats.draftPages} pages
            </div>
          </div>
          <div className="text-center">
            <div className="text-3xl font-bold text-green-400 mb-2">
              {stats.publishedArticles + stats.publishedEvents + stats.publishedPages}
            </div>
            <p className="text-white/70">Published</p>
            <div className="text-white/50 text-xs mt-1">
              {stats.publishedArticles} articles, {stats.publishedEvents} events, {stats.publishedPages} pages
            </div>
          </div>
          <div className="text-center">
            <div className="text-3xl font-bold text-blue-400 mb-2">
              {stats.totalArticles + stats.totalEvents + stats.totalPages}
            </div>
            <p className="text-white/70">Total Content</p>
            <div className="text-white/50 text-xs mt-1">
              All content items combined
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
