import {
  Home,
  Users,
  FileText,
  CalendarPlus,
  DollarSign,
  Briefcase,
  CalendarClock,
  UserCheck,
  Repeat,
  Wallet,
  ClipboardList,
  ListChecks,
  ShoppingCart,
  ShoppingBag,
  Package,
} from 'lucide-react';

import { getSession } from '@/lib/auth';
import { getEmployeeLandingPath, hasEmployeePermission } from '@/lib/employee-permissions';
import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import { PlaceHolderImages } from '@/lib/placeholder-images';
import { cn } from '@/lib/utils';
import { MobileNavMenu } from './mobile-nav-menu';
import { SidebarNav } from './sidebar-nav';

export default async function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await getSession();
  const user = session?.user;
  if (!user) return null; // Should be handled by middleware, but good practice

  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tDashboard = t.DashboardLayout;
  const isRtl = locale === 'ar';
  const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings() as Record<string, unknown>;
  const appName = String(settings.appName || t.Global.appName);
  const appLogoUrl = String(settings.appLogoUrl || '') || undefined;
  const businessMode = String(settings?.businessMode || '').trim();
  const realEstateEnabled = businessMode === 'real-estate' || businessMode === 'hybrid' || settings?.realEstateEnabled === true || settings?.realEstateEnabled === 'true';

  const isAdmin = user.role === 'admin';
  const isPos = user.role === 'pos';
  const employeeCashAccountCode = String(user.employeeCashAccountCode || '').trim();
  const landingPath = getEmployeeLandingPath(user, settings);
  const canManageSettings = hasEmployeePermission(user, settings, 'settings.manage');

  let pendingLeaveRequestsCount = 0;
  let pendingAdvanceRequestsCount = 0;
  let pendingAttendanceCorrectionsCount = 0;
  let myPendingAttendanceCorrectionsCount = 0;
  
  let myTasksCount = 0;
  let pendingWorkTransfersCount = 0;
  let pendingOverageApprovalsCount = 0;
  if (!isPos) {
    myTasksCount = 0;
    pendingWorkTransfersCount = 0;
    pendingOverageApprovalsCount = 0;
  }

  try {
    const { pgGetAttendanceCorrectionRequests } = await import('@/lib/postgres/attendance');

    if (isAdmin && (hasEmployeePermission(user, settings, 'admin.hr-attendance') || hasEmployeePermission(user, settings, 'admin.employees'))) {
      const pendingResult = await pgGetAttendanceCorrectionRequests({
        page: 1,
        pageSize: 1,
        status: 'pending',
      });
      pendingAttendanceCorrectionsCount = Number(pendingResult.total || 0);
    }

    if (!isAdmin && !isPos && user?.id) {
      const myPendingResult = await pgGetAttendanceCorrectionRequests({
        page: 1,
        pageSize: 1,
        employeeId: user.id,
        status: 'pending',
      });
      myPendingAttendanceCorrectionsCount = Number(myPendingResult.total || 0);
    }
  } catch {
    pendingAttendanceCorrectionsCount = 0;
    myPendingAttendanceCorrectionsCount = 0;
  }

  const navLinks = [
    ...(isPos
      ? [
          { href: '/admin/sales/pos', label: tDashboard?.sales ?? 'المبيعات', iconName: 'ShoppingCart' },
        ]
      : [
          {
            href: landingPath,
            label: tDashboard?.dashboard ?? 'لوحة التحكم',
            iconName: 'Home',
          },
        ]),
    ...(isAdmin
      ? [
          ...((hasEmployeePermission(user, settings, 'admin.employees') || hasEmployeePermission(user, settings, 'admin.leave-requests') || hasEmployeePermission(user, settings, 'admin.advance-requests') || hasEmployeePermission(user, settings, 'admin.shifts') || hasEmployeePermission(user, settings, 'admin.production')) ? [{
            href: '/admin/employees',
            label: 'إدارة الموظفين',
            iconName: 'Users',
            children: [
              ...(hasEmployeePermission(user, settings, 'admin.employees') ? [{ href: '/admin/employees', label: tDashboard?.employees ?? 'الموظفون', iconName: 'Users' }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.leave-requests') ? [{ href: '/admin/leave-requests', label: tDashboard?.leaveRequests ?? 'طلبات الإجازة', iconName: 'CalendarPlus', badge: pendingLeaveRequestsCount > 0 ? pendingLeaveRequestsCount : null }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.advance-requests') ? [{ href: '/admin/advance-requests', label: tDashboard?.advanceRequests ?? 'طلبات السلف', iconName: 'Wallet', badge: pendingAdvanceRequestsCount > 0 ? pendingAdvanceRequestsCount : null }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.shifts') ? [{ href: '/admin/shifts', label: tDashboard?.shiftManagement ?? 'إدارة الورديات', iconName: 'CalendarClock' }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.hr-attendance') ? [{ href: '/admin/hr/attendance', label: 'الحضور والانصراف', iconName: 'CalendarClock' }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.hr-attendance') ? [{ href: '/admin/hr/attendance/devices', label: 'أجهزة البصمة (Devices)', iconName: 'ListChecks' }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.hr-attendance') ? [{ href: '/admin/hr/attendance/enrollment', label: 'ربط الموظفين (Enrollment)', iconName: 'Users' }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.hr-attendance') ? [{ href: '/admin/hr/attendance/logs', label: 'سجلات البصمة (Logs)', iconName: 'ClipboardList' }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.hr-attendance') ? [{ href: '/admin/hr/attendance/corrections', label: 'طلبات تصحيح الحضور', iconName: 'ClipboardList', badge: pendingAttendanceCorrectionsCount > 0 ? pendingAttendanceCorrectionsCount : null }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.production') ? [{ href: '/admin/production', label: tDashboard?.production ?? 'الإنتاج', iconName: 'ClipboardList' }] : []),
            ],
          }] : []),
          ...((hasEmployeePermission(user, settings, 'admin.sales') || hasEmployeePermission(user, settings, 'admin.pos') || hasEmployeePermission(user, settings, 'admin.purchases') || hasEmployeePermission(user, settings, 'admin.work-tasks')) ? [{
            href: '/admin/sales',
            label: 'السندات',
            iconName: 'FileText',
            children: [
              ...(hasEmployeePermission(user, settings, 'admin.sales') ? [{ href: '/admin/sales', label: tDashboard?.sales ?? 'المبيعات', iconName: 'ShoppingCart' }] : []),
              ...(hasEmployeePermission(user, settings, 'admin.purchases') ? [{ href: '/admin/purchases', label: tDashboard?.purchases ?? 'المشتريات', iconName: 'Package' }] : []),
            ],
          }] : []),
          ...(hasEmployeePermission(user, settings, 'admin.pos') ? [{ href: '/admin/sales/pos', label: tDashboard?.pos ?? 'نقطة بيع', iconName: 'ShoppingCart' }] : []),
          ...(hasEmployeePermission(user, settings, 'admin.work-tasks') ? [{
            href: '/employee/work-tasks',
            label: tDashboard?.workTasks ?? 'مهام العمل',
            iconName: 'ClipboardCheck',
            badge: (pendingWorkTransfersCount + pendingOverageApprovalsCount) > 0 ? (pendingWorkTransfersCount + pendingOverageApprovalsCount) : null,
          }] : []),
          ...(realEstateEnabled
            ? [{ href: '/admin/data/real-estate', label: tDashboard?.realEstateProjects ?? 'المشاريع العقارية', iconName: 'Building' }]
            : []),
          ...(hasEmployeePermission(user, settings, 'admin.checks') ? [{
            href: '/admin/checks/incoming',
            label: 'إدارة الشيكات',
            iconName: 'Wallet',
            children: [
              {
                href: '/admin/checks/incoming',
                label: 'الشيكات الواردة',
                iconName: 'ListChecks',
              },
            ],
          }] : []),
          ...(hasEmployeePermission(user, settings, 'admin.accounting')
            ? [
                { href: '/admin/accounting/chart', label: tDashboard?.accounting ?? 'المحاسبة', iconName: 'FileText' },
                { href: '/admin/accounting/entries', label: tDashboard?.journalEntries ?? 'القيود المحاسبية', iconName: 'FileText' },
                { href: '/admin/accounting/bank-reconciliation', label: 'التسوية البنكية', iconName: 'Wallet' },
              ]
            : []),
          ...((hasEmployeePermission(user, settings, 'admin.monitoring') || hasEmployeePermission(user, settings, 'admin.dashboard')) ? [{ href: '/admin/monitoring', label: 'مراقبة', iconName: 'BarChart2' }] : []),
          ...(hasEmployeePermission(user, settings, 'admin.materials') ? [{ href: '/admin/data/materials', label: tDashboard?.itemLists ?? 'قوائم الأصناف', iconName: 'ListChecks' }] : []),
          ...(hasEmployeePermission(user, settings, 'admin.parties') ? [{ href: '/admin/data/parties', label: tDashboard?.partiesList ?? 'العملاء و الموردين', iconName: 'Users' }] : []),
          {
            href: '/admin/reports/operations',
            label: tDashboard?.reports ?? 'التقارير',
            iconName: 'BarChart2',
          },
          {
            href: '/store',
            label: 'المتجر',
            iconName: 'ShoppingBag',
            children: [
              { href: '/store', label: 'واجهة المتجر', iconName: 'ShoppingBag' },
              { href: '/admin/store/orders', label: 'إدارة الطلبات', iconName: 'Package' },
            ],
          },
        ]
      : []),
    ...(!isAdmin && !isPos
      ? [
          ...(hasEmployeePermission(user, settings, 'employee.dashboard') ? [{
            href: '/employee/dashboard',
            label: tDashboard?.payStub ?? 'قسيمة الدفع',
            iconName: 'FileText',
          }] : []),
          ...(hasEmployeePermission(user, settings, 'employee.dashboard') ? [{
            href: '/employee/attendance/history',
            label: 'سجل الحضور',
            iconName: 'CalendarClock',
            badge: myPendingAttendanceCorrectionsCount > 0 ? myPendingAttendanceCorrectionsCount : null,
          }] : []),
          ...(hasEmployeePermission(user, settings, 'employee.statement') ? [{
            href: '/employee/statement',
            label: tDashboard?.accountStatement ?? 'كشف حساب',
            iconName: 'Briefcase',
          }] : []),
          ...(hasEmployeePermission(user, settings, 'employee.leave') ? [{
            href: '/employee/leave',
            label: tDashboard?.leaveRequest ?? 'طلب إجازة',
            iconName: 'CalendarPlus',
          }] : []),
          ...(hasEmployeePermission(user, settings, 'employee.advance') ? [{
            href: '/employee/advance',
            label: tDashboard?.salaryAdvance ?? 'طلب سلفة',
            iconName: 'DollarSign',
          }] : []),
          ...(hasEmployeePermission(user, settings, 'employee.shift-swap') ? [{
            href: '/employee/shift-swap',
            label: tDashboard?.shiftSwap ?? 'تبديل وردية',
            iconName: 'Repeat',
          }] : []),
          ...(hasEmployeePermission(user, settings, 'employee.work-tasks') ? [{ 
            href: '/employee/work-tasks', 
            label: tDashboard?.workTasks ?? 'مهام العمل', 
            iconName: 'ClipboardCheck',
            badge: pendingWorkTransfersCount > 0 ? pendingWorkTransfersCount : null 
          }] : []),
          ...(hasEmployeePermission(user, settings, 'employee.my-tasks') ? [{ 
            href: '/employee/my-tasks', 
            label: tDashboard?.myTasks ?? 'مهامي', 
            iconName: 'UserCheck',
            badge: myTasksCount > 0 ? myTasksCount : null 
          }] : []),
        ]
      : []),
    ...(canManageSettings ? [{ href: '/settings', label: tDashboard?.settings ?? 'الإعدادات', iconName: 'Settings' }] : []),
  ];

  const userAvatarId =
    user.id === '1'
      ? 'admin-avatar'
      : user.id === '2'
      ? 'employee-1-avatar'
      : 'employee-2-avatar';
  const userAvatar = PlaceHolderImages.find((img) => img.id === userAvatarId);

  const userInitial = user.name.charAt(0).toUpperCase();

  return (
    <div className="flex min-h-screen w-full flex-col bg-muted/40 sm:flex-row">
      <SidebarNav 
        navLinks={navLinks}
        appName={appName}
        appLogoUrl={appLogoUrl}
        isPos={isPos}
        isAdmin={isAdmin}
        employeeCashAccountCode={employeeCashAccountCode}
        currentLocale={locale}
        languageT={t.Settings}
        userName={user.name}
        userInitial={userInitial}
        userAvatarUrl={userAvatar?.imageUrl}
        userAvatarHint={userAvatar?.imageHint}
        settingsLabel={tDashboard?.settings ?? 'الإعدادات'}
        supportLabel={tDashboard?.support ?? 'الدعم'}
        logoutLabel={tDashboard?.logout ?? 'تسجيل الخروج'}
      />
      <div data-dashboard-content className={cn("flex flex-1 flex-col sm:gap-4 sm:py-4")} suppressHydrationWarning>
        <header className="sticky top-0 z-30 flex h-14 items-center gap-4 border-b bg-card px-4 empty:hidden sm:hidden">
          <MobileNavMenu 
            navLinks={navLinks}
            appName={appName}
            appLogoUrl={appLogoUrl}
            isRtl={isRtl}
            isPos={isPos}
            isAdmin={isAdmin}
            employeeCashAccountCode={employeeCashAccountCode}
            currentLocale={locale}
            languageT={t.Settings}
            userName={user.name}
            userInitial={userInitial}
            userAvatarUrl={userAvatar?.imageUrl}
            userAvatarHint={userAvatar?.imageHint}
            settingsLabel={tDashboard?.settings ?? 'الإعدادات'}
            supportLabel={tDashboard?.support ?? 'الدعم'}
            logoutLabel={tDashboard?.logout ?? 'تسجيل الخروج'}
          />
        </header>
        <main data-dashboard-main className="grid flex-1 items-start gap-4 p-4 sm:px-6 sm:py-0 md:gap-8">
          {children}
        </main>
      </div>
    </div>
  );
}
