import Link from "next/link";
import DashboardLayout from "@/components/layout/dashboard-layout";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Users, Wallet, TrendingDown, TrendingUp, Building2, AlertTriangle, CalendarClock, Activity, Clock, AlertCircle, CheckCircle2, Zap } from "lucide-react";
import { verifySession } from "@/lib/auth";
import MonthYearPicker from "@/components/admin/month-year-picker";
import CashboxShiftBreakdownDialog from "@/components/admin/cashbox-shift-breakdown-dialog";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import { formatCurrency as formatCurrencyUtil } from "@/lib/currency-formatter";
import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";
import { format } from "date-fns";
import { getMonthlyBonuses, getMonthlyDeductions, getNetSalary } from "@/lib/data-helpers";
import { hasEmployeePermission } from "@/lib/employee-permissions";
import { getTranslations, getCurrentLocale } from "@/lib/i18n";
import type { RealEstateProject } from "@/lib/types";
import { handleTransferEmployeeCashboxToMain } from "@/lib/actions";
import { getPosShiftSessionsFresh } from "@/lib/data";

function buildRealEstateAlertSummary(projects: RealEstateProject[] = []) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const soonThreshold = new Date(today);
  soonThreshold.setDate(soonThreshold.getDate() + 7);

  const alerts = projects.flatMap((project) =>
    (Array.isArray(project?.units) ? project.units : []).flatMap((unit, unitIndex) => {
      const unitName = String(unit?.name || unit?.unitCode || `Unit ${unitIndex + 1}`).trim();
      const buyerName = String(unit?.buyerName || '').trim() || 'غير محدد';
      const installments = Array.isArray(unit?.installments) ? unit.installments : [];

      return installments
        .map((installment, installmentIndex) => {
          const amount = Math.max(0, Number(installment?.amount || 0));
          const paidAmount = Math.max(0, Number(installment?.paidAmount || 0));
          const remaining = Math.max(0, amount - paidAmount);
          const dueDate = String(installment?.dueDate || '').trim().slice(0, 10);
          if (!dueDate || remaining <= 0) return null;

          const dueTime = new Date(`${dueDate}T00:00:00`);
          dueTime.setHours(0, 0, 0, 0);
          const status = dueTime.getTime() < today.getTime()
            ? 'overdue'
            : dueTime.getTime() <= soonThreshold.getTime()
              ? 'due-soon'
              : 'upcoming';

          return {
            projectName: String(project?.name || project?.code || 'مشروع عقاري').trim(),
            unitName,
            buyerName,
            dueDate,
            amount,
            remaining,
            status,
            title: String(installment?.title || `قسط ${installmentIndex + 1}`).trim(),
          };
        })
        .filter(Boolean);
    })
  ).sort((left, right) => String(left?.dueDate || '').localeCompare(String(right?.dueDate || '')));

  const overdueAlerts = alerts.filter((alert) => alert?.status === 'overdue');
  const dueSoonAlerts = alerts.filter((alert) => alert?.status === 'due-soon');
  const urgentAlerts = alerts.filter((alert) => alert?.status === 'overdue' || alert?.status === 'due-soon');
  const totalUrgentAmount = urgentAlerts.reduce((sum, alert) => sum + Math.max(0, Number(alert?.remaining || 0)), 0);
  const affectedProjects = new Set(urgentAlerts.map((alert) => String(alert?.projectName || '').trim()).filter(Boolean)).size;

  return {
    alerts,
    urgentAlerts,
    overdueCount: overdueAlerts.length,
    dueSoonCount: dueSoonAlerts.length,
    totalUrgentAmount,
    affectedProjects,
  };
}

type ActivityItem = {
  id: string;
  type: 'invoice' | 'payment' | 'user' | 'system' | 'alert' | 'action';
  action: string;
  description: string;
  timestamp: string;
  severity: 'info' | 'warning' | 'critical';
  userOrSource?: string;
  related?: string;
};

function getActivityIcon(type: ActivityItem['type'], severity: ActivityItem['severity']) {
  if (severity === 'critical') return <AlertCircle className="h-4 w-4 text-red-600" />;
  if (severity === 'warning') return <AlertTriangle className="h-4 w-4 text-amber-600" />;
  if (type === 'invoice') return <Activity className="h-4 w-4 text-blue-600" />;
  if (type === 'payment') return <CheckCircle2 className="h-4 w-4 text-green-600" />;
  if (type === 'alert') return <Zap className="h-4 w-4 text-yellow-600" />;
  return <Clock className="h-4 w-4 text-gray-600" />;
}

function formatTimeAgo(dateString: string): string {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / (1000 * 60));
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

  if (diffMins < 1) return 'الآن';
  if (diffMins < 60) return `${diffMins} دقيقة`;
  if (diffHours < 24) return `${diffHours} ساعة`;
  if (diffDays < 7) return `${diffDays} يوم`;
  return format(date, 'dd/MM/yyyy HH:mm');
}

function formatShiftDateTime(value?: string) {
  const raw = String(value || '').trim();
  if (!raw) return '-';
  const date = new Date(raw);
  if (Number.isNaN(date.getTime())) return '-';
  return format(date, 'dd/MM HH:mm');
}

export default async function AdminDashboardPage({
  searchParams,
}: {
  searchParams?: Promise<{ month?: string; year?: string; cashboxTransfer?: string; cashboxReadyEmployeeId?: string }>;
}) {
  const session = await verifySession();
  const user = session.user;

  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global;
  const tAdminDashboard = t.AdminDashboard;
  const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();
  if (!user || !hasEmployeePermission(user, settings, 'admin.dashboard')) {
    return (
        <DashboardLayout>
            <div className="text-center">
                <h1 className="text-2xl font-bold">{tGlobal.accessDenied}</h1>
                <p>{tGlobal.noPermission}</p>
            </div>
        </DashboardLayout>
    );
  }

  const params = await searchParams;
  const cashboxTransferStatus = String(params?.cashboxTransfer || '').trim();
  const cashboxReadyEmployeeId = String(params?.cashboxReadyEmployeeId || '').trim();
  const today = new Date();
  const year = params?.year ? parseInt(params.year) : today.getFullYear();
  const month = params?.month ? parseInt(params.month) - 1 : today.getMonth();
  const selectedDate = new Date(year, month);

  const allEmployees = (await (await import('@/lib/postgres/data-access')).pgGetEmployees({ page: 1, pageSize: 5000 })).items as any[];
  const allJournalEntries = (await (await import('@/lib/postgres/data-access')).pgGetJournalEntries({ page: 1, pageSize: 10000 })).items as any[];
  const activeEmployees = allEmployees.length;
  const totalNetSalary = allEmployees.reduce((sum, employee) => sum + getNetSalary(employee, month, year), 0);
  const totalDeductions = allEmployees.reduce((sum, employee) => sum + getMonthlyDeductions(employee, month, year).total, 0);
  const totalBonuses = allEmployees.reduce((sum, employee) => sum + getMonthlyBonuses(employee, month, year).total, 0);
  const currencySymbol = await getCurrencySymbolAsync();
  const formatAmount = (amount: number) => formatCurrencyUtil(amount, currencySymbol);
  const shiftSessionsRaw = getPosShiftSessionsFresh() as Array<Record<string, unknown>>;

  const balanceByCode = new Map<string, number>();
  allJournalEntries.forEach((entry) => {
    (entry?.lines || []).forEach((line: any) => {
      const code = String(line?.accountCode || '').trim();
      if (!code) return;
      const nextBalance = (balanceByCode.get(code) || 0) + Number(line?.debit || 0) - Number(line?.credit || 0);
      balanceByCode.set(code, Math.round(nextBalance * 100) / 100);
    });
  });

  const latestShiftByUser = new Map<string, { status: 'active' | 'closed'; startedAt: string; endedAt?: string }>();
  const closedShiftBreakdownByUser = new Map<string, Array<{
    id: string;
    startedAt: string;
    endedAt?: string;
    openingCash: number;
    cashSalesAmount: number;
    expectedCashAtClose: number;
    countedCashAtClose?: number;
    cashVariance?: number;
    cashVarianceHandled?: boolean;
  }>>();
  shiftSessionsRaw.forEach((entry) => {
    const userId = String(entry?.userId || '').trim();
    const startedAt = String(entry?.startedAt || '').trim();
    if (!userId || !startedAt) return;

    const status = String(entry?.status || '').trim() === 'closed' ? 'closed' : 'active';
    const endedAt = String(entry?.endedAt || '').trim() || undefined;
    const current = latestShiftByUser.get(userId);
    if (!current || startedAt > current.startedAt) {
      latestShiftByUser.set(userId, { status, startedAt, endedAt });
    }

    const startedDate = new Date(startedAt);
    const isInSelectedMonth = !Number.isNaN(startedDate.getTime())
      && startedDate.getMonth() === month
      && startedDate.getFullYear() === year;

    if (status === 'closed' && isInSelectedMonth) {
      const openingCash = Number(entry?.openingCash || 0);
      const cashSalesAmount = Number(entry?.cashSalesAmount || 0);
      const expectedCashAtCloseRaw = Number(entry?.expectedCashAtClose);
      const expectedCashAtClose = Number.isFinite(expectedCashAtCloseRaw)
        ? expectedCashAtCloseRaw
        : openingCash + cashSalesAmount;
      const countedCashAtCloseRaw = Number(entry?.countedCashAtClose);
      const cashVarianceRaw = Number(entry?.cashVariance);
      const cashVarianceHandled = entry?.cashVarianceHandled === true;

      const currentBreakdown = closedShiftBreakdownByUser.get(userId) || [];
      currentBreakdown.push({
        id: String(entry?.id || `${userId}-${startedAt}`),
        startedAt,
        endedAt,
        openingCash,
        cashSalesAmount,
        expectedCashAtClose,
        countedCashAtClose: Number.isFinite(countedCashAtCloseRaw) ? countedCashAtCloseRaw : undefined,
        cashVariance: Number.isFinite(cashVarianceRaw) ? cashVarianceRaw : 0,
        cashVarianceHandled,
      });
      closedShiftBreakdownByUser.set(userId, currentBreakdown);
    }
  });

  closedShiftBreakdownByUser.forEach((items, userId) => {
    const sortedItems = [...items].sort((left, right) => String(right.startedAt).localeCompare(String(left.startedAt)));
    closedShiftBreakdownByUser.set(userId, sortedItems);
  });

  const cashierCashboxes = allEmployees.map((employee) => {
    const employeeId = String(employee?.id || '').trim();
    const cashCode = String(employee?.employeeCashAccountCode || '').trim();
    const cashBalance = cashCode ? (balanceByCode.get(cashCode) || 0) : 0;
    const latestShift = latestShiftByUser.get(employeeId);
    const closedShiftBreakdown = closedShiftBreakdownByUser.get(employeeId) || [];
    const pendingCashVariance = closedShiftBreakdown.reduce(
      (sum, shift: any) => {
        if (shift?.cashVarianceHandled === true) return sum;
        return sum + Number(shift?.cashVariance || 0);
      },
      0,
    );
    const roundedPendingCashVariance = Math.round(pendingCashVariance * 100) / 100;
    const closedShiftsInSelectedMonth = closedShiftBreakdown.length;
    const shiftStatus = latestShift?.status || 'none';
    const shiftStartedAt = latestShift?.startedAt;
    const shiftEndedAt = latestShift?.endedAt;
    return {
      id: employeeId,
      name: String(employee?.name || 'غير محدد'),
      cashCode,
      cashBalance,
      shiftStatus,
      shiftStartedAt,
      shiftEndedAt,
      closedShiftsInSelectedMonth,
      closedShiftBreakdown,
      pendingCashVariance: roundedPendingCashVariance,
    };
  });

  async function transferCashboxAction(formData: FormData) {
    'use server';
    const employeeId = String(formData.get('employeeId') || '').trim();
    const monthParam = String(formData.get('month') || '').trim();
    const yearParam = String(formData.get('year') || '').trim();
    const refreshedEmployeeId = String(formData.get('refreshedEmployeeId') || '').trim();
    const differenceDecision = String(formData.get('differenceDecision') || '').trim();

    const nextParams = new URLSearchParams();
    if (monthParam) nextParams.set('month', monthParam);
    if (yearParam) nextParams.set('year', yearParam);

    if (!employeeId) {
      nextParams.set('cashboxTransfer', 'invalid');
      redirect(`/admin/dashboard?${nextParams.toString()}`);
    }

    if (!refreshedEmployeeId || refreshedEmployeeId !== employeeId || cashboxReadyEmployeeId !== employeeId) {
      nextParams.set('cashboxTransfer', 'refresh-required');
      redirect(`/admin/dashboard?${nextParams.toString()}`);
    }

    const result = await handleTransferEmployeeCashboxToMain(employeeId, {
      source: 'dashboard',
      selectedMonth: Number(monthParam || 0),
      selectedYear: Number(yearParam || 0),
      differenceDecision: differenceDecision as 'post_cash_difference' | 'charge_cashier' | 'transfer_without_difference_entry' | 'abort_transfer',
    });
    if (result && 'success' in result && result.success) {
      if ('cashDifferenceAccountAutoCreated' in result && result.cashDifferenceAccountAutoCreated) {
        nextParams.set('cashboxTransfer', 'success-auto-created-cash-difference-account');
      } else {
        nextParams.set('cashboxTransfer', 'success');
      }
    } else if (result && 'error' in result && result.error === 'POS_SHIFT_MUST_BE_CLOSED') {
      nextParams.set('cashboxTransfer', 'shift-open');
    } else if (result && 'error' in result && result.error === 'CASHBOX_TRANSFER_DIFFERENCE_DECISION_REQUIRED') {
      nextParams.set('cashboxTransfer', 'difference-decision-required');
    } else if (result && 'error' in result && result.error === 'CASHBOX_TRANSFER_CHARGE_CASHIER_ONLY_FOR_SHORTAGE') {
      nextParams.set('cashboxTransfer', 'difference-shortage-policy-invalid');
    } else if (result && 'error' in result && result.error === 'CASHBOX_TRANSFER_ABORTED_BY_MANAGER') {
      nextParams.set('cashboxTransfer', 'difference-aborted');
    } else if (result && 'error' in result && result.error === 'CASH_DIFFERENCE_ACCOUNT_NOT_CONFIGURED') {
      nextParams.set('cashboxTransfer', 'cash-difference-account-missing');
    } else if (result && 'error' in result && result.error === 'EMPLOYEE_RECEIVABLE_ACCOUNT_NOT_CONFIGURED') {
      nextParams.set('cashboxTransfer', 'employee-receivable-account-missing');
    } else {
      nextParams.set('cashboxTransfer', 'error');
    }
    revalidatePath('/admin/dashboard');
    redirect(`/admin/dashboard?${nextParams.toString()}`);
  }

  async function refreshCashboxAction(formData: FormData) {
    'use server';
    const employeeId = String(formData.get('employeeId') || '').trim();
    const monthParam = String(formData.get('month') || '').trim();
    const yearParam = String(formData.get('year') || '').trim();

    const nextParams = new URLSearchParams();
    if (monthParam) nextParams.set('month', monthParam);
    if (yearParam) nextParams.set('year', yearParam);

    if (!employeeId) {
      nextParams.set('cashboxTransfer', 'invalid');
      redirect(`/admin/dashboard?${nextParams.toString()}`);
    }

    nextParams.set('cashboxTransfer', 'refreshed');
    nextParams.set('cashboxReadyEmployeeId', employeeId);
    revalidatePath('/admin/dashboard');
    redirect(`/admin/dashboard?${nextParams.toString()}`);
  }

  const canViewAttendanceCorrections =
    hasEmployeePermission(user, settings, 'admin.hr-attendance') ||
    hasEmployeePermission(user, settings, 'admin.employees');

  let attendanceCorrectionSla = {
    pendingCount: 0,
    warningCount: 0,
    criticalCount: 0,
  };

  if (canViewAttendanceCorrections) {
    try {
      const { pgGetAttendanceCorrectionRequests } = await import('@/lib/postgres/attendance');
      const pending = await pgGetAttendanceCorrectionRequests({
        page: 1,
        pageSize: 5000,
        status: 'pending',
      });

      const nowMs = Date.now();
      const items = (pending.items || []) as Array<{ created_at?: string }>;

      let warningCount = 0;
      let criticalCount = 0;
      for (const item of items) {
        const createdAtMs = new Date(String(item.created_at || '')).getTime();
        if (!Number.isFinite(createdAtMs)) continue;
        const hours = Math.max(0, Math.floor((nowMs - createdAtMs) / (1000 * 60 * 60)));
        if (hours >= 48) {
          criticalCount += 1;
        } else if (hours >= 24) {
          warningCount += 1;
        }
      }

      attendanceCorrectionSla = {
        pendingCount: items.length,
        warningCount,
        criticalCount,
      };
    } catch {
      attendanceCorrectionSla = {
        pendingCount: 0,
        warningCount: 0,
        criticalCount: 0,
      };
    }
  }

  // جلب بيانات المشاريع العقارية فقط إذا كان businessMode يتضمن العقارات
  const realEstateProjectsResult = (settings.businessMode === 'real-estate' || settings.businessMode === 'hybrid')
    ? await (await import('@/lib/actions')).handleGetRealEstateProjects()
    : null;
  const realEstateProjects = realEstateProjectsResult && 'success' in realEstateProjectsResult && realEstateProjectsResult.success
    ? (((realEstateProjectsResult as any).items || []) as RealEstateProject[])
    : [];
  const realEstateAlerts = buildRealEstateAlertSummary(realEstateProjects);

  return (
    <DashboardLayout>
      <div className="w-full max-w-7xl mx-auto">
        <div className="flex justify-between items-center mb-4">
          <h1 className="text-2xl font-bold">{tAdminDashboard.title}</h1>
          <MonthYearPicker initialDate={selectedDate} basePath="/admin/dashboard" />
        </div>
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{tAdminDashboard.activeEmployees}</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{activeEmployees}</div>
              <p className="text-xs text-muted-foreground">{tAdminDashboard.activeEmployeesDesc}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{tAdminDashboard.totalPayroll.replace('{monthName}', format(selectedDate, 'MMMM'))}</CardTitle>
              <Wallet className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatAmount(totalNetSalary)}</div>
              <p className="text-xs text-muted-foreground">{tAdminDashboard.totalPayrollDesc}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{tAdminDashboard.monthlyDeductions}</CardTitle>
              <TrendingDown className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-red-600">{formatAmount(totalDeductions)}</div>
              <p className="text-xs text-muted-foreground">{tAdminDashboard.monthlyDeductionsDesc.replace('{monthName}', format(selectedDate, 'MMMM'))}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{tAdminDashboard.monthlyBonuses}</CardTitle>
              <TrendingUp className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">{formatAmount(totalBonuses)}</div>
              <p className="text-xs text-muted-foreground">{tAdminDashboard.monthlyBonusesDesc.replace('{monthName}', format(selectedDate, 'MMMM'))}</p>
            </CardContent>
          </Card>
        </div>

        <div className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">ترحيل صناديق الكاشير</CardTitle>
            </CardHeader>
            <CardContent>
              {cashboxTransferStatus === 'success' && (
                <div className="mb-4 rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">
                  تم ترحيل الرصيد إلى الصندوق الرئيسي بنجاح.
                </div>
              )}
              {cashboxTransferStatus === 'success-auto-created-cash-difference-account' && (
                <div className="mb-4 rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">
                  تم ترحيل الرصيد بنجاح، وتم إنشاء حساب فروقات الصندوق تلقائيًا داخل شجرة الحسابات.
                </div>
              )}
              {cashboxTransferStatus === 'error' && (
                <div className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                  تعذر ترحيل الرصيد. تحقق من وجود رصيد موجب أو إعداد الصندوق.
                </div>
              )}
              {cashboxTransferStatus === 'invalid' && (
                <div className="mb-4 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
                  بيانات الترحيل غير مكتملة. أعد المحاولة.
                </div>
              )}
              {cashboxTransferStatus === 'shift-open' && (
                <div className="mb-4 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
                  لا يمكن الترحيل قبل إغلاق الوردية الخاصة بالكاشير.
                </div>
              )}
              {cashboxTransferStatus === 'refreshed' && (
                <div className="mb-4 rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-700">
                  تم تحديث بيانات الصندوق. يمكنك الآن تنفيذ الترحيل للصندوق المحدد.
                </div>
              )}
              {cashboxTransferStatus === 'refresh-required' && (
                <div className="mb-4 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
                  يجب الضغط على زر تحديث أولاً قبل السماح بالترحيل إلى الرئيسي.
                </div>
              )}
              {cashboxTransferStatus === 'difference-decision-required' && (
                <div className="mb-4 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
                  يوجد فارق في الصندوق. يجب على المدير اختيار سياسة معالجة الفارق قبل الترحيل.
                </div>
              )}
              {cashboxTransferStatus === 'difference-shortage-policy-invalid' && (
                <div className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                  خيار تحميل النقص على الكاشير متاح فقط عند وجود نقص فعلي، وليس عند الزيادة.
                </div>
              )}
              {cashboxTransferStatus === 'difference-aborted' && (
                <div className="mb-4 rounded-md border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700">
                  تم إيقاف عملية الترحيل بناءً على قرار المدير.
                </div>
              )}
              {cashboxTransferStatus === 'cash-difference-account-missing' && (
                <div className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                  لا يمكن معالجة الفارق لأن حساب فروقات الصندوق غير موجود في شجرة الحسابات.
                </div>
              )}
              {cashboxTransferStatus === 'employee-receivable-account-missing' && (
                <div className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                  لا يمكن تحميل النقص على الكاشير لأن حساب ذمم الموظفين غير مهيأ في شجرة الحسابات.
                </div>
              )}
              <div className="mb-1 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                {cashierCashboxes.map((cashbox) => (
                  <div key={`dashboard-cashbox-${cashbox.id}`} className="rounded-lg border bg-muted/20 p-4">
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <p className="font-medium">{cashbox.name}</p>
                        <p className="text-xs text-muted-foreground">{cashbox.cashCode || 'بدون صندوق مرتبط'}</p>
                        <p className="mt-1 text-xs text-muted-foreground">
                          {cashbox.shiftStatus === 'none'
                            ? 'لا توجد وردية مسجلة'
                            : `الوردية: من ${formatShiftDateTime(cashbox.shiftStartedAt)} إلى ${cashbox.shiftStatus === 'active' ? 'الآن' : formatShiftDateTime(cashbox.shiftEndedAt)}`}
                        </p>
                      </div>
                      <div className="flex flex-col items-end gap-1">
                        <Badge variant={cashbox.cashBalance > 0 ? 'default' : 'secondary'}>{formatAmount(cashbox.cashBalance)}</Badge>
                        <Badge variant={cashbox.shiftStatus === 'active' ? 'destructive' : 'secondary'}>
                          {cashbox.shiftStatus === 'active' ? 'الوردية مفتوحة' : cashbox.shiftStatus === 'closed' ? 'الوردية مغلقة' : 'بدون وردية'}
                        </Badge>
                      </div>
                    </div>
                    {cashbox.cashCode && (
                      <div className="mt-2">
                        <CashboxShiftBreakdownDialog
                          employeeName={cashbox.name}
                          currencySymbol={currencySymbol}
                          shifts={cashbox.closedShiftBreakdown}
                          currentCashBalance={cashbox.cashBalance}
                        />
                      </div>
                    )}
                    <div className="mt-3 flex flex-wrap gap-2">
                      <form action={refreshCashboxAction}>
                        <input type="hidden" name="employeeId" value={cashbox.id} />
                        <input type="hidden" name="month" value={String(month + 1)} />
                        <input type="hidden" name="year" value={String(year)} />
                        <Button type="submit" variant="secondary" size="sm" disabled={!cashbox.cashCode}>
                          تحديث الصندوق
                        </Button>
                      </form>
                      <form action={transferCashboxAction}>
                        <input type="hidden" name="employeeId" value={cashbox.id} />
                        <input type="hidden" name="month" value={String(month + 1)} />
                        <input type="hidden" name="year" value={String(year)} />
                        <input type="hidden" name="refreshedEmployeeId" value={cashboxReadyEmployeeId} />
                        {Math.abs(Number(cashbox.pendingCashVariance || 0)) > 0.009 && (
                          <select
                            name="differenceDecision"
                            defaultValue=""
                            className="mb-2 h-8 w-full rounded-md border bg-background px-2 text-xs"
                            required
                          >
                            <option value="" disabled>اختر إجراء الفارق</option>
                            <option value="post_cash_difference">
                              {cashbox.pendingCashVariance > 0
                                ? 'تسجيل زيادة الجرد إلى حساب فروقات الصندوق'
                                : 'تسجيل نقص الجرد على حساب فروقات الصندوق'}
                            </option>
                            {cashbox.pendingCashVariance < 0 && (
                              <option value="charge_cashier">تحميل النقص على ذمم الموظف</option>
                            )}
                            <option value="transfer_without_difference_entry">ترحيل بدون معالجة الفارق الآن</option>
                            <option value="abort_transfer">إيقاف الترحيل الآن</option>
                          </select>
                        )}
                        <Button
                          type="submit"
                          variant="outline"
                          size="sm"
                          disabled={!cashbox.cashCode || cashbox.cashBalance <= 0 || cashbox.shiftStatus === 'active' || cashboxReadyEmployeeId !== cashbox.id}
                        >
                          ترحيل إلى الرئيسي
                        </Button>
                      </form>
                    </div>
                    {cashbox.cashCode && cashbox.shiftStatus !== 'active' && cashboxReadyEmployeeId !== cashbox.id && (
                      <p className="mt-2 text-xs text-amber-700">يلزم تحديث هذا الصندوق أولاً قبل الترحيل.</p>
                    )}
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>

        {canViewAttendanceCorrections && (
          <div className="mt-6">
            <Card className={attendanceCorrectionSla.criticalCount > 0 ? 'border-red-300' : attendanceCorrectionSla.warningCount > 0 ? 'border-amber-300' : ''}>
              <CardHeader className="flex flex-row items-start justify-between gap-3">
                <div>
                  <CardTitle className="text-base">تنبيهات تصحيح الحضور</CardTitle>
                  <p className="text-sm text-muted-foreground mt-1">مراقبة الطلبات المعلقة حسب SLA (تحذير 24 ساعة - حرج 48 ساعة)</p>
                </div>
                <Link href="/admin/hr/attendance/corrections" className="text-sm text-primary hover:underline">
                  فتح طلبات التصحيح
                </Link>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
                  <div className="rounded-md border p-3">
                    <div className="text-muted-foreground">إجمالي المعلق</div>
                    <div className="text-2xl font-bold">{attendanceCorrectionSla.pendingCount}</div>
                  </div>
                  <div className="rounded-md border border-amber-200 bg-amber-50 p-3">
                    <div className="text-amber-700">تحذير (24h+)</div>
                    <div className="text-2xl font-bold text-amber-700">{attendanceCorrectionSla.warningCount}</div>
                  </div>
                  <div className="rounded-md border border-red-200 bg-red-50 p-3">
                    <div className="text-red-700">حرج (48h+)</div>
                    <div className="text-2xl font-bold text-red-700">{attendanceCorrectionSla.criticalCount}</div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {/* قسم مراقبة الأنشطة والتنبيهات اللحظية */}
        <div className="mt-8">
          <Card className="border-blue-100">
            <CardHeader className="bg-gradient-to-r from-blue-50 to-cyan-50 pb-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Activity className="h-5 w-5 text-blue-600" />
                  <CardTitle className="text-lg">مراقبة الأنشطة الحالية</CardTitle>
                </div>
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <div className="h-2 w-2 rounded-full bg-green-500 animate-pulse"></div>
                  <span>مراقبة فعالة</span>
                </div>
              </div>
              <p className="text-sm text-muted-foreground mt-2">
                تتبع آخر الإجراءات والتغييرات الهامة مع تنبيهات لحظية عن الحالات الحرجة
              </p>
            </CardHeader>
            <CardContent className="pt-6">
              {/* نموذج أنشطة - في الإنتاج ستكون من قاعدة البيانات */}
              <div className="space-y-3 max-h-96 overflow-y-auto">
                {/* نشاط حرج 1 */}
                <div className="flex items-start gap-3 p-3 rounded-lg border border-red-200 bg-red-50/50 hover:bg-red-50 transition-colors">
                  <div className="mt-0.5">{getActivityIcon('alert', 'critical')}</div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between gap-2">
                      <p className="font-medium text-sm">فاتورة مبيعات منتهية الصلاحية</p>
                      <span className="text-xs bg-red-100 text-red-700 px-2 py-1 rounded-full">حرج</span>
                    </div>
                    <p className="text-xs text-muted-foreground mt-1">الفاتورة #2024-1847 لم تُسدد بعد {formatTimeAgo(new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString())}</p>
                    <p className="text-xs text-red-700 font-medium mt-1">مبلغ: 5,250.00 ₪ • العميل: شركة الأمل</p>
                  </div>
                </div>

                {/* نشاط تحذير 1 */}
                <div className="flex items-start gap-3 p-3 rounded-lg border border-amber-200 bg-amber-50/50 hover:bg-amber-50 transition-colors">
                  <div className="mt-0.5">{getActivityIcon('invoice', 'warning')}</div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between gap-2">
                      <p className="font-medium text-sm">دفعة مستحقة قريباً</p>
                      <span className="text-xs bg-amber-100 text-amber-700 px-2 py-1 rounded-full">تحذير</span>
                    </div>
                    <p className="text-xs text-muted-foreground mt-1">قسط (وحدة 402-B) مستحق بعد يومين {formatTimeAgo(new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString())}</p>
                    <p className="text-xs text-amber-700 font-medium mt-1">مبلغ: 2,500.00 ₪ • المشروع: الواحة الخضراء</p>
                  </div>
                </div>

                {/* نشاط معلومات 1 */}
                <div className="flex items-start gap-3 p-3 rounded-lg border border-green-200 bg-green-50/50 hover:bg-green-50 transition-colors">
                  <div className="mt-0.5">{getActivityIcon('payment', 'info')}</div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between gap-2">
                      <p className="font-medium text-sm">دفعة تم استلامها</p>
                      <span className="text-xs bg-green-100 text-green-700 px-2 py-1 rounded-full">إكمال</span>
                    </div>
                    <p className="text-xs text-muted-foreground mt-1">الفاتورة #2024-1901 من شركة النجاح {formatTimeAgo(new Date(Date.now() - 15 * 60 * 1000).toISOString())}</p>
                    <p className="text-xs text-green-700 font-medium mt-1">مبلغ: 8,750.00 ₪ • الحالة: مسددة</p>
                  </div>
                </div>

                {/* نشاط معلومات 2 */}
                <div className="flex items-start gap-3 p-3 rounded-lg border border-blue-200 bg-blue-50/50 hover:bg-blue-50 transition-colors">
                  <div className="mt-0.5">{getActivityIcon('user', 'info')}</div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between gap-2">
                      <p className="font-medium text-sm">فاتورة مبيعات جديدة</p>
                      <span className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full">إنشاء</span>
                    </div>
                    <p className="text-xs text-muted-foreground mt-1">الفاتورة #2024-1915 من قبل أحمد محمود {formatTimeAgo(new Date(Date.now() - 45 * 60 * 1000).toISOString())}</p>
                    <p className="text-xs text-blue-700 font-medium mt-1">المبلغ: 3,200.00 ₪ • العميل: مطعم الرويال</p>
                  </div>
                </div>

                {/* نشاط معلومات 3 */}
                <div className="flex items-start gap-3 p-3 rounded-lg border border-gray-200 bg-gray-50/50 hover:bg-gray-50 transition-colors">
                  <div className="mt-0.5">{getActivityIcon('system', 'info')}</div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between gap-2">
                      <p className="font-medium text-sm">مردود مبيعات مسجل</p>
                      <span className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded-full">نظام</span>
                    </div>
                    <p className="text-xs text-muted-foreground mt-1">الفاتورة #2024-1912 - مرتجع جزئي {formatTimeAgo(new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString())}</p>
                    <p className="text-xs text-gray-700 font-medium mt-1">المبلغ: 450.00 ₪ • المسؤول: فاطمة علي</p>
                  </div>
                </div>
              </div>

              {/* ملخص الأنشطة اليومية */}
              <div className="mt-6 pt-4 border-t border-gray-200 grid grid-cols-1 md:grid-cols-4 gap-3">
                <div className="text-center">
                  <div className="text-xl font-bold text-red-600">3</div>
                  <p className="text-xs text-muted-foreground">حالات حرجة</p>
                </div>
                <div className="text-center">
                  <div className="text-xl font-bold text-amber-600">5</div>
                  <p className="text-xs text-muted-foreground">تحذيرات</p>
                </div>
                <div className="text-center">
                  <div className="text-xl font-bold text-green-600">12</div>
                  <p className="text-xs text-muted-foreground">عمليات ناجحة</p>
                </div>
                <div className="text-center">
                  <div className="text-xl font-bold text-blue-600">28</div>
                  <p className="text-xs text-muted-foreground">إجمالي الأنشطة</p>
                </div>
              </div>

              <div className="mt-4 flex justify-center">
                <Link href="/admin/activity-log" className="text-sm text-primary hover:underline font-medium">
                  عرض سجل الأنشطة الكامل ←
                </Link>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </DashboardLayout>
  );
}
