"use client"

import { useEffect, useState, useCallback } from "react"
import Link from "next/link"
import {
  Users,
  Newspaper,
  CalendarDays,
  FolderOpen,
  Image,
  MessageSquare,
  Coins,
  Clock,
  Loader2,
  Plus,
  CalendarCheck,
  UserCheck,
  FolderCog,
  ImagePlus,
  MessageCircle,
  Bell,
  Trash2,
  Eye,
  TrendingUp,
  ArrowUpRight,
  Activity,
} from "lucide-react"

interface Stats {
  members: number
  pendingMembers: number
  news: number
  events: number
  projects: number
  gallery: number
  contacts: number
  donationsTotal: number
  committees: number
  partners: number
  faqs: number
  boardMembers: number
}

interface Notification {
  id: string
  titleAr: string
  messageAr: string
  type: string
  isRead: boolean
  createdAt: string
}

const quickActions = [
  { label: "إضافة خبر", href: "/ai.admin/news", icon: Plus, gradient: "from-[#1A3A6B] to-[#2B5EA7]" },
  { label: "إنشاء حدث", href: "/ai.admin/events", icon: CalendarCheck, gradient: "from-[#2E7D32] to-[#4CAF50]" },
  { label: "عرض الأعضاء", href: "/ai.admin/members", icon: UserCheck, gradient: "from-[#D4A843] to-[#E0BC6A]" },
  { label: "إدارة المشاريع", href: "/ai.admin/projects", icon: FolderCog, gradient: "from-[#7B1FA2] to-[#AB47BC]" },
  { label: "المعرض", href: "/ai.admin/gallery", icon: ImagePlus, gradient: "from-[#C2185B] to-[#E91E63]" },
  { label: "الرسائل", href: "/ai.admin/contacts", icon: MessageCircle, gradient: "from-[#D84315] to-[#FF7043]" },
]

export default function AdminDashboard() {
  const [stats, setStats] = useState<Stats | null>(null)
  const [notifications, setNotifications] = useState<Notification[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchNotifications = useCallback(async () => {
    try {
      const res = await fetch("/api/admin/notifications?limit=10")
      const data = await res.json()
      setNotifications(data.data || [])
    } catch {}
  }, [])

  useEffect(() => {
    Promise.all([
      fetch("/api/admin/stats").then((res) => {
        if (!res.ok) throw new Error("Failed to fetch stats")
        return res.json()
      }),
      fetchNotifications(),
    ])
      .then(([statsData]) => setStats(statsData))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }, [fetchNotifications])

  const markAsRead = async (id: string) => {
    await fetch(`/api/admin/notifications/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isRead: true }),
    })
    fetchNotifications()
  }

  const deleteNotification = async (id: string) => {
    await fetch(`/api/admin/notifications/${id}`, { method: "DELETE" })
    fetchNotifications()
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="flex flex-col items-center gap-3">
          <Loader2 className="w-8 h-8 text-[#1A3A6B] animate-spin" />
          <p className="text-sm text-gray-500">جاري تحميل البيانات...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-2xl p-6 text-red-700 flex items-center gap-3">
        <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
          <span className="text-red-600 font-bold">!</span>
        </div>
        <div>
          <p className="font-medium">خطأ في تحميل لوحة التحكم</p>
          <p className="text-sm text-red-600">{error}</p>
        </div>
      </div>
    )
  }

  const statCards = [
    { label: "إجمالي الأعضاء", value: stats?.members ?? 0, icon: Users, gradient: "from-[#1A3A6B] to-[#2B5EA7]", textColor: "text-[#1A3A6B]" },
    { label: "أعضاء معلقون", value: stats?.pendingMembers ?? 0, icon: Clock, gradient: "from-[#D4A843] to-[#E0BC6A]", textColor: "text-[#D4A843]" },
    { label: "أخبار منشورة", value: stats?.news ?? 0, icon: Newspaper, gradient: "from-[#2E7D32] to-[#4CAF50]", textColor: "text-[#2E7D32]" },
    { label: "أحداث قادمة", value: stats?.events ?? 0, icon: CalendarDays, gradient: "from-[#7B1FA2] to-[#AB47BC]", textColor: "text-[#7B1FA2]" },
    { label: "مشاريع نشطة", value: stats?.projects ?? 0, icon: FolderOpen, gradient: "from-[#0277BD] to-[#039BE5]", textColor: "text-[#0277BD]" },
    { label: "المعرض", value: stats?.gallery ?? 0, icon: Image, gradient: "from-[#C2185B] to-[#E91E63]", textColor: "text-[#C2185B]" },
    { label: "رسائل الاتصال", value: stats?.contacts ?? 0, icon: MessageSquare, gradient: "from-[#D84315] to-[#FF7043]", textColor: "text-[#D84315]" },
    { label: "التبرعات", value: stats?.donationsTotal ?? 0, icon: Coins, gradient: "from-[#F57F17] to-[#FFCA28]", textColor: "text-[#F57F17]", isCurrency: true },
  ]

  const getTypeColor = (type: string) => {
    switch (type) {
      case "success": return "bg-emerald-100 text-emerald-600"
      case "warning": return "bg-amber-100 text-amber-600"
      case "error": return "bg-red-100 text-red-600"
      default: return "bg-blue-100 text-blue-600"
    }
  }

  const getTypeIcon = (type: string) => {
    switch (type) {
      case "success": return "✓"
      case "warning": return "⚠"
      case "error": return "✕"
      default: return "ℹ"
    }
  }

  const getTimeAgo = (date: string) => {
    const now = new Date()
    const notifDate = new Date(date)
    const diffMs = now.getTime() - notifDate.getTime()
    const diffMins = Math.floor(diffMs / 60000)
    const diffHours = Math.floor(diffMins / 60)
    const diffDays = Math.floor(diffHours / 24)

    if (diffMins < 1) return "الآن"
    if (diffMins < 60) return `منذ ${diffMins} دقيقة`
    if (diffHours < 24) return `منذ ${diffHours} ساعة`
    return `منذ ${diffDays} يوم`
  }

  return (
    <div className="space-y-6">
      {/* Welcome Banner */}
      <div className="bg-gradient-to-l from-[#1A3A6B] via-[#2B5EA7] to-[#1A3A6B] rounded-2xl p-6 text-white relative overflow-hidden">
        <div className="absolute inset-0 opacity-10">
          <div className="absolute top-0 right-0 w-32 h-32 bg-white rounded-full -translate-y-1/2 translate-x-1/2" />
          <div className="absolute bottom-0 left-0 w-24 h-24 bg-white rounded-full translate-y-1/2 -translate-x-1/2" />
        </div>
        <div className="relative">
          <h1 className="text-2xl font-bold mb-2">مرحباً بك في لوحة التحكم</h1>
          <p className="text-white/80 text-sm">رابطة خريجي جامعة أفريقيا العالمية - إدارة محتوى الموقع والنظام</p>
          <div className="flex items-center gap-4 mt-4">
            <div className="flex items-center gap-2 bg-white/10 px-3 py-1.5 rounded-lg">
              <Activity className="w-4 h-4" />
              <span className="text-sm">{stats?.members ?? 0} عضو مسجل</span>
            </div>
            <div className="flex items-center gap-2 bg-white/10 px-3 py-1.5 rounded-lg">
              <TrendingUp className="w-4 h-4" />
              <span className="text-sm">{stats?.pendingMembers ?? 0} طلب معلق</span>
            </div>
          </div>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map((card, index) => {
          const Icon = card.icon
          return (
            <div key={index} className="bg-white dark:bg-[#1a2332] rounded-2xl shadow-sm dark:shadow-[0_2px_8px_rgba(0,0,0,0.4)] border border-gray-100 dark:border-[#2a3d56] p-5 hover:shadow-md dark:hover:shadow-[0_4px_12px_rgba(0,0,0,0.5)] transition-all group">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500 dark:text-[#94a3b8] mb-1">{card.label}</p>
                  <p className={`text-2xl font-bold ${card.textColor}`}>
                    {card.isCurrency
                      ? `${card.value.toLocaleString()} ج.س`
                      : card.value.toLocaleString()}
                  </p>
                </div>
                <div className={`p-3 rounded-xl bg-gradient-to-br ${card.gradient} text-white shadow-lg group-hover:scale-110 transition-transform`}>
                  <Icon className="w-6 h-6" />
                </div>
              </div>
            </div>
          )
        })}
      </div>

      {/* Quick Actions */}
      <div className="bg-white dark:bg-[#1a2332] rounded-2xl shadow-sm dark:shadow-[0_2px_8px_rgba(0,0,0,0.4)] border border-gray-100 dark:border-[#2a3d56] p-6">
        <h2 className="text-lg font-bold text-gray-800 dark:text-[#f1f5f9] mb-4 flex items-center gap-2">
          <div className="w-1 h-5 bg-[#D4A843] rounded-full" />
          إجراءات سريعة
        </h2>
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
          {quickActions.map((action) => {
            const Icon = action.icon
            return (
              <Link
                key={action.href}
                href={action.href}
                className={`flex flex-col items-center justify-center gap-3 p-5 text-white rounded-2xl bg-gradient-to-br ${action.gradient} hover:shadow-lg hover:scale-105 transition-all`}
              >
                <Icon className="w-7 h-7" />
                <span className="text-sm font-medium text-center">{action.label}</span>
              </Link>
            )
          })}
        </div>
      </div>

      {/* Notifications */}
      <div className="bg-white dark:bg-[#1a2332] rounded-2xl shadow-sm dark:shadow-[0_2px_8px_rgba(0,0,0,0.4)] border border-gray-100 dark:border-[#2a3d56] p-6">
        <div className="flex items-center justify-between mb-5">
          <h2 className="text-lg font-bold text-gray-800 dark:text-[#f1f5f9] flex items-center gap-2">
            <div className="w-1 h-5 bg-[#1A3A6B] rounded-full" />
            آخر الإشعارات
          </h2>
          <Link
            href="/ai.admin/notifications"
            className="text-sm text-[#1A3A6B] dark:text-[#60a5fa] hover:text-[#2B5EA7] dark:hover:text-[#93c5fd] flex items-center gap-1 font-medium transition-colors"
          >
            عرض الكل
            <ArrowUpRight className="w-4 h-4" />
          </Link>
        </div>
        <div className="space-y-2">
          {notifications.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-[#94a3b8]">
              <Bell className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-[#3b4f6b]" />
              <p className="font-medium">لا توجد إشعارات جديدة</p>
              <p className="text-sm text-gray-400 dark:text-[#7a8ba3] mt-1">ستظهر الإشعارات هنا عند وصولها</p>
            </div>
          ) : (
            notifications.slice(0, 8).map((notif) => (
              <div
                key={notif.id}
                className={`flex items-start gap-3 p-3 rounded-xl transition-all ${
                  !notif.isRead
                    ? "bg-[#1A3A6B]/5 dark:bg-[#1a3050] border border-[#1A3A6B]/10 dark:border-[#2a4a6b]"
                    : "hover:bg-gray-50 dark:hover:bg-[#1e2d42] border border-transparent dark:border-transparent"
                }`}
              >
                <div className={`w-9 h-9 rounded-xl flex items-center justify-center text-sm shrink-0 ${getTypeColor(notif.type)}`}>
                  {getTypeIcon(notif.type)}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <p className={`text-sm truncate ${!notif.isRead ? "font-bold text-gray-900 dark:text-[#ffffff]" : "font-medium text-gray-700 dark:text-[#e2e8f0]"}`}>
                      {notif.titleAr}
                    </p>
                    {!notif.isRead && <div className="w-2 h-2 bg-[#D4A843] rounded-full shrink-0" />}
                  </div>
                  <p className="text-xs text-gray-500 dark:text-[#94a3b8] truncate mt-0.5">{notif.messageAr}</p>
                  <p className="text-[10px] text-gray-400 dark:text-[#7a8ba3] mt-1">{getTimeAgo(notif.createdAt)}</p>
                </div>
                <div className="flex items-center gap-1 shrink-0">
                  {!notif.isRead && (
                    <button
                      onClick={() => markAsRead(notif.id)}
                      className="p-1.5 hover:bg-gray-200 dark:hover:bg-[#2a3d56] rounded-lg text-gray-400 dark:text-[#94a3b8] hover:text-[#1A3A6B] dark:hover:text-[#60a5fa] transition-colors"
                      title="تعليم كمقروء"
                    >
                      <Eye className="w-3.5 h-3.5" />
                    </button>
                  )}
                  <button
                    onClick={() => deleteNotification(notif.id)}
                    className="p-1.5 hover:bg-gray-200 dark:hover:bg-[#2a3d56] rounded-lg text-gray-400 dark:text-[#94a3b8] hover:text-red-600 dark:hover:text-[#f87171] transition-colors"
                    title="حذف"
                  >
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  )
}
