'use client'

import { useState, useEffect, useRef } from 'react'
import Image from 'next/image'
import logoImage from '@/assets/logo.png'
import ProtectedRoute from '@/components/ProtectedRoute'
import { useAuth } from '@/contexts/AuthContext'
import { useLanguage } from '@/contexts/LanguageContext'
import LanguageSwitcher from '@/components/LanguageSwitcher'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import {
  Users,
  User,
  TrendingUp,
  Package,
  CheckSquare,
  UserCheck,
  Megaphone,
  LogOut,
  Building2,
  Settings,
  Bell,
  Shield,
  FileText,
  Truck
} from 'lucide-react'
import { dashboardAPI, notificationsAPI } from '@/lib/api'
import { portalAPI } from '@/lib/api/portal'
import { hrAdminAPI } from '@/lib/api/hrAdmin'

function DashboardContent() {
    const { user, logout, hasPermission } = useAuth()
  const router = useRouter()
  const { t, language, dir } = useLanguage()

  const [stats, setStats] = useState({
    contacts: 0,
    activeTasks: 0,
    notifications: 0,
  })

  const [showNotifications, setShowNotifications] = useState(false)
  const [notifications, setNotifications] = useState<any[]>([])
  const [notificationsLoading, setNotificationsLoading] = useState(false)
  const notificationsRef = useRef<HTMLDivElement | null>(null)

  const [pendingApprovals, setPendingApprovals] = useState({
    managedLeaves: 0,
    managedOvertime: 0,
    purchaseRequests: 0,
    total: 0,
  })

  useEffect(() => {
    dashboardAPI
      .getStats()
      .then((res) => {
        if (res.data?.data) setStats(res.data.data)
      })
      .catch(() => {})
  }, [])

  const loadNotifications = async () => {
    setNotificationsLoading(true)
    try {
      const res = await notificationsAPI.getMy({ page: 1, pageSize: 10 })
      const items = res.data?.data?.notifications || []
      setNotifications(items)
    } catch {
      setNotifications([])
    } finally {
      setNotificationsLoading(false)
    }
  }

  const markNotificationAsRead = async (id: string) => {
    try {
      await notificationsAPI.markAsRead(id)

      setNotifications((prev) =>
        prev.map((item) =>
          item.id === id
            ? { ...item, isRead: true, readAt: new Date().toISOString() }
            : item
        )
      )

      setStats((prev) => ({
        ...prev,
        notifications: Math.max(0, prev.notifications - 1),
      }))
    } catch {}
  }

   const resolveNotificationUrl = (notification: any) => {
    if (notification.entityType === 'LEAVE') {
      if (notification.type === 'LEAVE_REQUEST_SUBMITTED') {
        return '/portal/managed-leaves';
      }
      return '/portal/leave';
    }

    if (notification.entityType === 'OVERTIME_REQUEST') {
      if (notification.type === 'OVERTIME_REQUEST_SUBMITTED') {
        return '/portal/managed-overtime-requests';
      }
      return '/portal/overtime';
    }

    if (notification.entityType === 'PURCHASE_REQUEST') {
      if (notification.type === 'PURCHASE_REQUEST_SUBMITTED') {
        return '/hr?tab=purchases';
      }
      return '/portal/purchase-requests';
    }

    if (notification.entityType === 'LOAN') {
      if (
        notification.type === 'LOAN_REQUEST_SUBMITTED' ||
        notification.type === 'LOAN_REQUEST_PENDING_ADMIN'
      ) {
        return '/hr?tab=loans';
      }
      return '/portal/loans';
    }

    if (notification.entityType === 'EXPENSE_CLAIM') {
      if (notification.entityId) {
        if (notification.type === 'EXPENSE_CLAIM_SUBMITTED') {
          return `/portal/managed-expense-claims?claimId=${notification.entityId}`;
        }

        if (
          notification.type === 'EXPENSE_CLAIM_CREATED' ||
          notification.type === 'EXPENSE_CLAIM_APPROVED' ||
          notification.type === 'EXPENSE_CLAIM_REJECTED'
        ) {
          return `/portal/expense-claims?claimId=${notification.entityId}`;
        }

        // fallback
        return `/portal/expense-claims?claimId=${notification.entityId}`;
      }

      return '/portal/expense-claims';
    }

    if (notification.type === 'TENDER_DIRECTIVE_ASSIGNED') {
      if (notification.entityType === 'TENDER' && notification.entityId) {
        return `/tenders/${notification.entityId}?tab=directives`;
      }

      return '/tenders';
    }

    return '/dashboard';
  };

  const handleNotificationClick = async (notification: any) => {
  try {
    if (!notification.isRead) {
      await markNotificationAsRead(notification.id)
    }

    const targetUrl = resolveNotificationUrl(notification)

    console.log('🔔 Notification click →', notification)
    console.log('➡️ Redirecting to:', targetUrl)

    setShowNotifications(false)

    router.push(targetUrl)

    setTimeout(() => {
      window.location.href = targetUrl
    }, 100)

  } catch (err) {
    console.error('Notification click error:', err)
  }
}

  const handleToggleNotifications = async () => {
    const next = !showNotifications
    setShowNotifications(next)

    if (next) {
      await loadNotifications()
    }
  }

  const loadPendingApprovals = async () => {
    try {
      const [managedLeaves, managedOvertime, purchaseRequests] = await Promise.all([
        canViewManagedLeaves
          ? portalAPI.getManagedLeaves('PENDING')
          : Promise.resolve([]),
        canViewManagedOvertime
          ? portalAPI.getManagedOvertimeRequests()
          : Promise.resolve([]),
        canApproveHr
          ? hrAdminAPI
              .getPurchaseRequests({ status: 'PENDING', page: 1, pageSize: 50 })
              .then((r) => r.purchaseRequests || [])
          : Promise.resolve([]),
      ])

      const total =
        managedLeaves.length +
        managedOvertime.length +
        purchaseRequests.length

      setPendingApprovals({
        managedLeaves: managedLeaves.length,
        managedOvertime: managedOvertime.length,
        purchaseRequests: purchaseRequests.length,
        total,
      })
    } catch {
      setPendingApprovals({
        managedLeaves: 0,
        managedOvertime: 0,
        purchaseRequests: 0,
        total: 0,
      })
    }
  }


  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        notificationsRef.current &&
        !notificationsRef.current.contains(event.target as Node)
      ) {
        setShowNotifications(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [])
    

  const allModules = [
    {
      id: 'contacts',
      name: 'إدارة جهات الاتصال',
      nameEn: 'Contact Management',
      icon: Users,
      color: 'bg-blue-500',
      href: '/contacts',
      description: 'إدارة العملاء وجهات الاتصال',
      permission: 'contacts'
    },
    {
      id: 'suppliers',
      name: 'إدارة الموردين',
      nameEn: 'Supplier Management',
      icon: Truck,
      color: 'bg-emerald-500',
      href: '/suppliers',
      description: 'إدارة الموردين وبيانات التواصل والاعتماد',
      permission: 'suppliers'
    },
    {
      id: 'crm',
      name: 'إدارة علاقات العملاء',
      nameEn: 'CRM',
      icon: TrendingUp,
      color: 'bg-green-500',
      href: '/crm',
      description: 'الفرص التجارية والعروض والصفقات',
      permission: 'crm'
    },
    {
      id: 'tenders',
      name: 'إدارة المناقصات',
      nameEn: 'Tender Management',
      icon: FileText,
      color: 'bg-indigo-500',
      href: '/tenders',
      description: 'تسجيل ومتابعة المناقصات وتحويلها إلى فرص',
      permission: 'tenders'
    },
    {
      id: 'inventory',
      name: 'المخزون والأصول',
      nameEn: 'Inventory & Assets',
      icon: Package,
      color: 'bg-purple-500',
      href: '/inventory',
      description: 'المنتجات والمخازن والأصول الثابتة',
      permission: 'inventory'
    },
    {
      id: 'projects',
      name: 'المهام والمشاريع',
      nameEn: 'Tasks & Projects',
      icon: CheckSquare,
      color: 'bg-orange-500',
      href: '/projects',
      description: 'إدارة المشاريع والمهام والموارد',
      permission: 'projects'
    },
    {
      id: 'hr',
      name: 'الموارد البشرية',
      nameEn: 'Human Resources',
      icon: UserCheck,
      color: 'bg-teal-500',
      href: '/hr',
      description: 'الموظفين والإجازات والرواتب',
      permission: 'hr'
    },
    {
      id: 'portal',
      name: 'البوابة الذاتية',
      nameEn: 'My Portal',
      icon: User,
      color: 'bg-cyan-500',
      href: '/portal',
      description: 'قروضي، إجازاتي، طلبات الشراء والرواتب',
      permission: 'portal'
    },
    {
      id: 'marketing',
      name: 'التسويق',
      nameEn: 'Marketing',
      icon: Megaphone,
      color: 'bg-pink-500',
      href: '/marketing',
      description: 'الحملات التسويقية والعملاء المحتملين',
      permission: 'marketing'
    },
    {
      id: 'admin',
      name: 'لوحة الإدارة',
      nameEn: 'Admin Panel',
      icon: Shield,
      color: 'bg-red-500',
      href: '/admin',
      description: 'إدارة المستخدمين والأدوار وسجل العمليات',
      permission: 'admin'
    }
  ]

  // Filter modules based on user permissions
  const availableModules = allModules.filter(module => 
    hasPermission(module.permission, 'view')
  )
  const canViewManagedLeaves = hasPermission('department_leave_requests', 'view')
  const canViewManagedOvertime = hasPermission('department_overtime_requests', 'view')
  const canApproveHr = hasPermission('hr', 'approve')

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
      {/* Header */}
      <header className="bg-white shadow-sm border-b sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Image
                src={logoImage}
                alt="Company Logo"
                width={48}
                height={48}
                className="object-contain"
                priority
              />
              <div>
                <h1 className="text-2xl font-bold text-gray-900">ATMATA</h1>
                <p className="text-sm text-gray-600">نظام إدارة علاقات العملاء</p>
              </div>
            </div>
            
            <div className="flex items-center gap-4">
              {/* Language Switcher */}
              <LanguageSwitcher />
              
              {/* User Info */}
              <div className="text-right">
                <p className="text-sm font-semibold text-gray-900">{user?.username}</p>
                <p className="text-xs text-gray-600">{user?.role?.name || 'مستخدم'}</p>
              </div>

              {/* Admin Panel Link - Only for admins */}
              {hasPermission('admin', 'view') && (
                <Link
                  href="/admin"
                  className="p-2 hover:bg-red-50 rounded-lg transition-colors relative group"
                  title="لوحة تحكم المدير"
                >
                  <Shield className="h-5 w-5 text-red-600" />
                  <span className="absolute -bottom-8 right-0 bg-red-600 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">
                    لوحة الإدارة
                  </span>
                </Link>
              )}

              {/* Notifications */}
              <div className="relative" ref={notificationsRef}>
                <button
                  onClick={handleToggleNotifications}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors relative"
                  title="الإشعارات"
                >
                  <Bell className="h-5 w-5 text-gray-600" />
                  {stats.notifications > 0 && (
                    <span className="absolute top-1 right-1 h-2 w-2 bg-red-500 rounded-full"></span>
                  )}
                </button>

                {showNotifications && (
                  <div className="absolute left-0 mt-2 w-96 bg-white border border-gray-200 rounded-xl shadow-xl z-50 overflow-hidden">
                    <div className="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
                      <h3 className="text-sm font-bold text-gray-900">الإشعارات</h3>
                      <button
                        onClick={async () => {
                          try {
                            await notificationsAPI.markAllAsRead()
                            setNotifications((prev) =>
                              prev.map((item) => ({
                                ...item,
                                isRead: true,
                                readAt: new Date().toISOString(),
                              }))
                            )
                            setStats((prev) => ({ ...prev, notifications: 0 }))
                          } catch {}
                        }}
                        className="text-xs text-blue-600 hover:text-blue-700"
                      >
                        تعليم الكل كمقروء
                      </button>
                    </div>

                    <div className="max-h-96 overflow-y-auto">
                      {notificationsLoading ? (
                        <div className="p-4 text-sm text-gray-500 text-center">
                          جاري تحميل الإشعارات...
                        </div>
                      ) : notifications.length === 0 ? (
                        <div className="p-4 text-sm text-gray-500 text-center">
                          لا توجد إشعارات
                        </div>
                      ) : (
                        <div className="divide-y divide-gray-100">
                          {notifications.map((notification) => (
                            <button
                              key={notification.id}
                              onClick={() => handleNotificationClick(notification)}
                              className={`w-full text-right px-4 py-3 hover:bg-gray-50 transition-colors ${
                                notification.isRead ? 'bg-white' : 'bg-blue-50'
                              }`}
                            >
                              <div className="flex items-start justify-between gap-3">
                                <div className="flex-1">
                                  <p className="text-sm font-semibold text-gray-900">
                                    {notification.title}
                                  </p>
                                  <p className="text-xs text-gray-600 mt-1">
                                    {notification.message}
                                  </p>
                                  <p className="text-[11px] text-gray-400 mt-2">
                                    {new Date(notification.createdAt).toLocaleString()}
                                  </p>
                                </div>

                                {!notification.isRead && (
                                  <span className="mt-1 h-2.5 w-2.5 rounded-full bg-blue-500 flex-shrink-0"></span>
                                )}
                              </div>
                            </button>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>

              {/* Settings */}
              <button className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
                <Settings className="h-5 w-5 text-gray-600" />
              </button>

              {/* Logout */}
              <button
                onClick={logout}
                className="flex items-center gap-2 px-4 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
              >
                <LogOut className="h-5 w-5" />
                <span className="font-medium">خروج</span>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Welcome Section */}
        <div className="bg-gradient-to-l from-primary-600 to-primary-700 rounded-2xl shadow-lg p-8 mb-8 text-white">
          <h2 className="text-3xl font-bold mb-2">مرحباً، {user?.username}! 👋</h2>
          <p className="text-primary-100 text-lg">
            {user?.role?.name} - {availableModules.length} وحدة متاحة
          </p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">الوحدات المتاحة</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{availableModules.length}</p>
              </div>
              <div className="bg-blue-100 p-3 rounded-lg">
                <Package className="h-8 w-8 text-blue-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">المهام النشطة</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{stats.activeTasks}</p>
              </div>
              <div className="bg-green-100 p-3 rounded-lg">
                <CheckSquare className="h-8 w-8 text-green-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">الإشعارات</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{stats.notifications}</p>
              </div>
              <div className="bg-orange-100 p-3 rounded-lg">
                <Bell className="h-8 w-8 text-orange-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">جهات الاتصال</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{stats.contacts}</p>
              </div>
              <div className="bg-purple-100 p-3 rounded-lg">
                <Users className="h-8 w-8 text-purple-600" />
              </div>
            </div>
          </div>
        </div>

                {/* Pending Approvals */}
        {pendingApprovals.total > 0 && (
          <div className="bg-white rounded-2xl shadow-md border border-gray-100 p-6 mb-8">
            <div className="flex items-center justify-between mb-5">
              <div>
                <h3 className="text-xl font-bold text-gray-900">بانتظار موافقتك</h3>
                <p className="text-sm text-gray-600 mt-1">
                  كل الطلبات التي تحتاج قرارك الآن
                </p>
              </div>

              <div className="bg-amber-100 text-amber-700 px-4 py-2 rounded-lg font-bold">
                {pendingApprovals.total}
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {canViewManagedLeaves && (
                <button
                  onClick={() => router.push('/portal/managed-leaves')}
                  className="text-right border border-gray-200 rounded-xl p-4 hover:bg-gray-50 transition-colors"
                >
                  <p className="text-sm text-gray-500">طلبات إجازات القسم</p>
                  <p className="text-2xl font-bold text-gray-900 mt-2">
                    {pendingApprovals.managedLeaves}
                  </p>
                  <p className="text-xs text-blue-600 mt-2">فتح الصفحة</p>
                </button>
              )}

              {canViewManagedOvertime && (
                <button
                  onClick={() => router.push('/portal/managed-overtime-requests')}
                  className="text-right border border-gray-200 rounded-xl p-4 hover:bg-gray-50 transition-colors"
                >
                  <p className="text-sm text-gray-500">طلبات الساعات الإضافية</p>
                  <p className="text-2xl font-bold text-gray-900 mt-2">
                    {pendingApprovals.managedOvertime}
                  </p>
                  <p className="text-xs text-blue-600 mt-2">فتح الصفحة</p>
                </button>
              )}

              {canApproveHr && (
                <button
                  onClick={() => router.push('/hr?tab=purchases')}
                  className="text-right border border-gray-200 rounded-xl p-4 hover:bg-gray-50 transition-colors"
                >
                  <p className="text-sm text-gray-500">طلبات الشراء</p>
                  <p className="text-2xl font-bold text-gray-900 mt-2">
                    {pendingApprovals.purchaseRequests}
                  </p>
                  <p className="text-xs text-blue-600 mt-2">فتح الصفحة</p>
                </button>
              )}
            </div>
          </div>
        )}

        {/* Available Modules */}
        <div className="mb-8">
          <h3 className="text-2xl font-bold text-gray-900 mb-6">الوحدات المتاحة</h3>
          
          {availableModules.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {availableModules.map((module) => {
                const Icon = module.icon
                return (
                  <Link
                    key={module.id}
                    href={module.href}
                    className="bg-white rounded-xl shadow-md hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1 p-6 border border-gray-200 group"
                  >
                    <div className="flex items-start gap-4">
                      <div className={`${module.color} p-3 rounded-lg group-hover:scale-110 transition-transform`}>
                        <Icon className="h-6 w-6 text-white" />
                      </div>
                      <div className="flex-1">
                        <h4 className="text-lg font-bold text-gray-900 mb-1">
                          {module.name}
                        </h4>
                        <p className="text-sm text-gray-500 mb-2">{module.nameEn}</p>
                        <p className="text-sm text-gray-600">{module.description}</p>
                      </div>
                    </div>
                  </Link>
                )
              })}
            </div>
          ) : (
            <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-8 text-center">
              <p className="text-yellow-800 text-lg">
                لا توجد وحدات متاحة لحسابك. الرجاء التواصل مع المسؤول لمنح الصلاحيات المناسبة.
              </p>
            </div>
          )}
        </div>

        {/* Recent Activity */}
        <div className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
          <h3 className="text-xl font-bold text-gray-900 mb-4">النشاط الأخير</h3>
          <p className="text-gray-500 text-center py-6">لا يوجد نشاط حديث</p>
        </div>
      </main>
    </div>
  )
}

export default function DashboardPage() {
  return (
    <ProtectedRoute>
      <DashboardContent />
    </ProtectedRoute>
  )
}

