'use client'

import ProtectedRoute from '@/components/ProtectedRoute'
import { useAuth } from '@/contexts/AuthContext'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import {
  LayoutDashboard,
  Banknote,
  Calendar,
  ShoppingCart,
  Clock,
  DollarSign,
  Building2,
  LogOut,
  User,
  FileText,
  CheckCircle2,
   TimerReset,
} from 'lucide-react'

function PortalLayoutContent({ children }: { children: React.ReactNode }) {
  const { user, logout, hasPermission } = useAuth()
  const pathname = usePathname()

  const menuItems = [
    { icon: LayoutDashboard, label: 'لوحة التحكم', labelEn: 'Dashboard', href: '/portal', exact: true },
    { icon: Banknote, label: 'قروضي', labelEn: 'My Loans', href: '/portal/loans' },
    { icon: Calendar, label: 'إجازاتي', labelEn: 'My Leave', href: '/portal/leave' },
    { icon: FileText, label: 'كشوف المصاريف', labelEn: 'Expense Claims', href: '/portal/expense-claims' },
    { icon: TimerReset, label: 'الساعات الإضافية', labelEn: 'Overtime', href: '/portal/overtime' },
    ...(hasPermission('department_overtime_requests', 'view')
      ? [{
          icon: CheckCircle2,
          label: 'طلبات الساعات الإضافية',
          labelEn: 'Department Overtime Requests',
          href: '/portal/managed-overtime-requests'
        }]
      : []),
          ...(hasPermission('department_expense_claims', 'view')
      ? [{
          icon: CheckCircle2,
          label: 'طلبات كشوف المصاريف',
          labelEn: 'Department Expense Claims',
          href: '/portal/managed-expense-claims'
        }]
      : []),
        ...(hasPermission('department_leave_requests', 'view')
            ? [{ icon: CheckCircle2, label: 'طلبات إجازات القسم', labelEn: 'Department Leave Requests', href: '/portal/managed-leaves' }]
            : []),    { icon: ShoppingCart, label: 'طلبات الشراء', labelEn: 'Purchase Requests', href: '/portal/purchase-requests' },
            { icon: Clock, label: 'حضوري', labelEn: 'My Attendance', href: '/portal/attendance' },
            { icon: DollarSign, label: 'رواتبي', labelEn: 'My Salaries', href: '/portal/salaries' },
          ]

  const isActive = (href: string, exact?: boolean) => {
    if (exact) return pathname === href
    return pathname.startsWith(href)
  }

  return (
    <div className="min-h-screen bg-gray-50 flex" dir="rtl">
      <aside className="w-64 bg-white border-l shadow-lg fixed h-full overflow-y-auto">
        <div className="p-6 border-b">
          <div className="flex items-center gap-3 mb-4">
            <div className="bg-teal-600 p-2 rounded-lg">
              <User className="h-6 w-6 text-white" />
            </div>
            <div>
              <h2 className="text-lg font-bold text-gray-900">البوابة الذاتية</h2>
              <p className="text-xs text-gray-600">Employee Portal</p>
            </div>
          </div>
          <div className="bg-teal-50 border border-teal-200 rounded-lg p-3">
            <p className="text-xs font-semibold text-teal-900">{user?.username}</p>
            <p className="text-xs text-teal-700">{user?.role?.name || 'موظف'}</p>
          </div>
        </div>

        <nav className="p-4">
          {menuItems.map((item) => {
            const Icon = item.icon
            const active = isActive(item.href, item.exact)
            return (
              <Link
                key={item.href}
                href={item.href}
                className={`flex items-center gap-3 px-4 py-3 rounded-lg mb-2 transition-all ${
                  active ? 'bg-teal-600 text-white shadow-md' : 'text-gray-700 hover:bg-gray-100'
                }`}
              >
                <Icon className="h-5 w-5" />
                <span className="font-medium">{item.label}</span>
              </Link>
            )
          })}

          <hr className="my-4 border-gray-200" />

          <Link
            href="/dashboard"
            className="flex items-center gap-3 px-4 py-3 rounded-lg mb-2 text-gray-700 hover:bg-gray-100 transition-all"
          >
            <Building2 className="h-5 w-5" />
            <span className="font-medium">العودة للنظام</span>
          </Link>

          <button
            onClick={logout}
            className="w-full flex items-center gap-3 px-4 py-3 rounded-lg text-red-600 hover:bg-red-50 transition-all"
          >
            <LogOut className="h-5 w-5" />
            <span className="font-medium">تسجيل الخروج</span>
          </button>
        </nav>
      </aside>

      <main className="mr-64 flex-1 p-8">
        {children}
      </main>
    </div>
  )
}

export default function PortalLayout({ children }: { children: React.ReactNode }) {
  return (
    <ProtectedRoute>
      <PortalLayoutContent>{children}</PortalLayoutContent>
    </ProtectedRoute>
  )
}
