import DashboardLayout from '@/components/layout/dashboard-layout';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { verifySession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { formatCurrency } from '@/lib/currency-formatter';
import { getCurrencySymbolAsync } from '@/lib/server-currency';
import { pgGetInventoryMovements, pgGetInvoices, pgGetJournalEntries, pgGetPayments, pgGetSettings } from '@/lib/postgres/data-access';

type EventSeverity = 'low' | 'medium' | 'high';
type EventSource = 'invoice' | 'payment' | 'journal' | 'inventory';
type EventSortKey =
  | 'date'
  | 'source'
  | 'type'
  | 'reference'
  | 'note'
  | 'actor'
  | 'severity'
  | 'score'
  | 'amount';
type SortDirection = 'asc' | 'desc';

type MonitoringEvent = {
  id: string;
  eventDate: string;
  eventDay: string;
  source: EventSource;
  eventType: string;
  referenceId: string;
  referenceNumber: string;
  actorName: string;
  amountBase: number;
  severity: EventSeverity;
  riskScore: number;
  riskReasons: string[];
  modificationNote: string;
  modificationBy: string;
  modificationAt: string;
  isModified: boolean;
  preview: string;
};

function toDay(value: string): string {
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) return '';
  return parsed.toISOString().slice(0, 10);
}

function round2(value: number): number {
  return Math.round((Number(value || 0) + Number.EPSILON) * 100) / 100;
}

function severityBadgeClass(severity: EventSeverity): string {
  if (severity === 'high') return 'bg-red-100 text-red-800';
  if (severity === 'medium') return 'bg-amber-100 text-amber-800';
  return 'bg-slate-100 text-slate-700';
}

function sourceLabel(source: EventSource): string {
  if (source === 'invoice') return 'فاتورة';
  if (source === 'payment') return 'دفعة';
  if (source === 'journal') return 'قيد';
  return 'مخزون';
}

function pickFirstString(source: any, keys: string[]): string {
  for (const key of keys) {
    const value = String(source?.[key] || '').trim();
    if (value) return value;
  }
  return '';
}

function inferUpdateAt(source: any): string {
  return pickFirstString(source, ['updatedAt', 'lastUpdatedAt', 'modifiedAt', 'editedAt', 'updated_at']);
}

function inferUpdateBy(source: any): string {
  return pickFirstString(source, ['updatedBy', 'lastUpdatedBy', 'modifiedBy', 'editedBy', 'updated_by']);
}

function wasUpdatedAfterCreate(createdAt: string, updatedAt: string): boolean {
  if (!createdAt || !updatedAt) return false;
  const createdMs = new Date(createdAt).getTime();
  const updatedMs = new Date(updatedAt).getTime();
  if (Number.isNaN(createdMs) || Number.isNaN(updatedMs)) return false;
  return updatedMs - createdMs > 60000;
}

function buildInvoiceEvents(invoices: any[]): MonitoringEvent[] {
  return invoices.map((invoice) => {
    const eventDate = String(invoice.date || invoice.createdAt || '');
    const grandTotal = Number(invoice.grandTotal || 0);
    const amountReceived = Number(invoice.amountReceived || 0);
    const amountDue = Number(invoice.amountDue || 0);
    const status = String(invoice.status || 'active').trim().toLowerCase();
    const riskReasons: string[] = [];

    if (status === 'cancelled') riskReasons.push('تم إلغاء الفاتورة');
    if (amountDue > grandTotal + 0.01) riskReasons.push('المتبقي أكبر من قيمة الفاتورة');
    if (amountReceived > grandTotal + 0.01) riskReasons.push('المدفوع أكبر من قيمة الفاتورة');

    const items = Array.isArray(invoice.items) ? invoice.items : [];
    const hasBadLine = items.some((line: any) => Number(line.quantity || 0) <= 0 || Number(line.unitPrice || 0) < 0);
    if (hasBadLine) riskReasons.push('بنود بكمية/سعر غير منطقي');

    const createdAt = String(invoice.createdAt || '');
    const updatedAt = inferUpdateAt(invoice);
    const updatedBy = inferUpdateBy(invoice);
    const cancelledReason = String(invoice.cancelledReason || '').trim();
    let modificationNote = 'إنشاء السند';
    let modificationBy = String(invoice.createdBy || '-');
    let modificationAt = eventDate;
    let isModified = false;

    if (status === 'cancelled') {
      modificationNote = cancelledReason ? `إلغاء السند: ${cancelledReason}` : 'إلغاء السند';
      modificationBy = String(invoice.cancelledBy || updatedBy || invoice.createdBy || '-');
      modificationAt = String(invoice.cancelledAt || updatedAt || eventDate);
      isModified = true;
    } else if (wasUpdatedAfterCreate(createdAt, updatedAt) || updatedBy) {
      modificationNote = 'تعديل بيانات الفاتورة';
      modificationBy = String(updatedBy || invoice.createdBy || '-');
      modificationAt = String(updatedAt || eventDate);
      isModified = true;
    } else if (invoice.lockedBy && invoice.lockedAt) {
      modificationNote = 'تم فتح السند للتعديل';
      modificationBy = String(invoice.lockedBy || '-');
      modificationAt = String(invoice.lockedAt || eventDate);
      isModified = true;
    }

    const riskScore = Math.min(100, riskReasons.length * 25 + (status === 'cancelled' ? 20 : 0));
    const severity: EventSeverity = riskScore >= 70 ? 'high' : riskScore >= 35 ? 'medium' : 'low';

    return {
      id: `invoice:${String(invoice.id || '')}`,
      eventDate,
      eventDay: toDay(eventDate),
      source: 'invoice' as const,
      eventType: status === 'cancelled' ? 'cancelled' : 'saved',
      referenceId: String(invoice.id || ''),
      referenceNumber: String(invoice.invoiceNumber || invoice.id || '-'),
      actorName: String(invoice.createdBy || '-'),
      amountBase: round2(Number(invoice.grandTotalBase || grandTotal)),
      severity,
      riskScore,
      riskReasons,
      modificationNote,
      modificationBy,
      modificationAt,
      isModified,
      preview: `العميل: ${String(invoice.customerName || '-')} | الإجمالي: ${round2(grandTotal).toFixed(2)}`,
    };
  });
}

function buildPaymentEvents(payments: any[]): MonitoringEvent[] {
  const duplicateBuckets = new Map<string, number>();
  for (const payment of payments) {
    const key = `${toDay(String(payment.date || ''))}|${String(payment.customerId || '')}|${round2(Number(payment.amount || 0)).toFixed(2)}`;
    duplicateBuckets.set(key, (duplicateBuckets.get(key) || 0) + 1);
  }

  return payments.map((payment) => {
    const eventDate = String(payment.date || payment.createdAt || '');
    const amount = Number(payment.amount || 0);
    const riskReasons: string[] = [];
    const allocations = Array.isArray(payment.allocations) ? payment.allocations : [];
    const allocated = allocations.reduce((sum: number, row: any) => sum + Number(row.amount || 0), 0);

    if (amount <= 0) riskReasons.push('دفعة بمبلغ غير صالح');
    if (allocated > amount + 0.01) riskReasons.push('تخصيصات الدفعة أكبر من مبلغ الدفعة');

    const duplicateKey = `${toDay(eventDate)}|${String(payment.customerId || '')}|${round2(amount).toFixed(2)}`;
    if ((duplicateBuckets.get(duplicateKey) || 0) > 1) riskReasons.push('دفعة مكررة محتملة بنفس اليوم ونفس المبلغ');

    const updatedAt = inferUpdateAt(payment);
    const updatedBy = inferUpdateBy(payment);
    const paymentStatus = String(payment.status || 'active').toLowerCase();
    const cancelledReason = String(payment.cancelledReason || '').trim();
    let modificationNote = 'إنشاء الدفعة';
    let modificationBy = String(payment.createdBy || '-');
    let modificationAt = eventDate;
    let isModified = false;

    if (paymentStatus === 'cancelled') {
      modificationNote = cancelledReason ? `إلغاء الدفعة: ${cancelledReason}` : 'إلغاء الدفعة';
      modificationBy = String(payment.cancelledBy || updatedBy || payment.createdBy || '-');
      modificationAt = String(payment.cancelledAt || updatedAt || eventDate);
      isModified = true;
    } else if (updatedAt || updatedBy) {
      modificationNote = 'تعديل بيانات الدفعة';
      modificationBy = String(updatedBy || payment.createdBy || '-');
      modificationAt = String(updatedAt || eventDate);
      isModified = true;
    } else if (allocations.length > 0) {
      modificationNote = `تعديل/تسجيل تخصيصات (${allocations.length}) على سندات المبيعات`;
      isModified = true;
    }

    const riskScore = Math.min(100, riskReasons.length * 30);
    const severity: EventSeverity = riskScore >= 70 ? 'high' : riskScore >= 35 ? 'medium' : 'low';

    return {
      id: `payment:${String(payment.id || '')}`,
      eventDate,
      eventDay: toDay(eventDate),
      source: 'payment' as const,
      eventType: String(payment.status || 'active').toLowerCase() === 'cancelled' ? 'cancelled' : 'received',
      referenceId: String(payment.id || ''),
      referenceNumber: String(payment.reference || payment.id || '-'),
      actorName: String(payment.createdBy || '-'),
      amountBase: round2(Number(payment.amountBase || amount)),
      severity,
      riskScore,
      riskReasons,
      modificationNote,
      modificationBy,
      modificationAt,
      isModified,
      preview: `العميل: ${String(payment.customerId || '-')} | المبلغ: ${round2(amount).toFixed(2)} | تخصيصات: ${allocations.length}`,
    };
  });
}

function buildJournalEvents(entries: any[]): MonitoringEvent[] {
  return entries.map((entry) => {
    const eventDate = String(entry.date || entry.createdAt || '');
    const lines = Array.isArray(entry.lines) ? entry.lines : [];
    const debit = lines.reduce((sum: number, line: any) => sum + Number(line.debit || 0), 0);
    const credit = lines.reduce((sum: number, line: any) => sum + Number(line.credit || 0), 0);
    const riskReasons: string[] = [];

    if (Math.abs(debit - credit) > 0.01) {
      riskReasons.push('قيد غير متوازن (مدين لا يساوي دائن)');
    }

    const status = String(entry.status || 'posted').toLowerCase();
    const updatedAt = inferUpdateAt(entry);
    const updatedBy = inferUpdateBy(entry);
    let modificationNote = 'إنشاء القيد';
    let modificationBy = String(entry.createdBy || '-');
    let modificationAt = eventDate;
    let isModified = false;

    if (status === 'reversed') {
      modificationNote = 'تم عكس القيد المحاسبي';
      modificationBy = String(updatedBy || entry.createdBy || '-');
      modificationAt = String(updatedAt || eventDate);
      isModified = true;
    } else if (updatedAt || updatedBy) {
      modificationNote = 'تعديل بيانات القيد';
      modificationBy = String(updatedBy || entry.createdBy || '-');
      modificationAt = String(updatedAt || eventDate);
      isModified = true;
    }

    const riskScore = Math.min(100, riskReasons.length * 50);
    const severity: EventSeverity = riskScore >= 70 ? 'high' : riskScore >= 35 ? 'medium' : 'low';

    return {
      id: `journal:${String(entry.id || '')}`,
      eventDate,
      eventDay: toDay(eventDate),
      source: 'journal' as const,
      eventType: String(entry.status || 'posted'),
      referenceId: String(entry.id || ''),
      referenceNumber: String(entry.id || '-'),
      actorName: String(entry.createdBy || '-'),
      amountBase: round2(Math.max(debit, credit)),
      severity,
      riskScore,
      riskReasons,
      modificationNote,
      modificationBy,
      modificationAt,
      isModified,
      preview: `مرجع: ${String(entry.referenceType || '-')} | مدين: ${round2(debit).toFixed(2)} | دائن: ${round2(credit).toFixed(2)}`,
    };
  });
}

function buildInventoryEvents(movements: any[]): MonitoringEvent[] {
  return movements.map((movement) => {
    const eventDate = String(movement.date || movement.movement_date || movement.createdAt || '');
    const qtyIn = Number(movement.quantityIn || movement.quantity_in || 0);
    const qtyOut = Number(movement.quantityOut || movement.quantity_out || 0);
    const riskReasons: string[] = [];

    if (qtyIn < 0 || qtyOut < 0) riskReasons.push('حركة مخزون بكميات سالبة');
    if (qtyIn > 0 && qtyOut > 0) riskReasons.push('حركة تحتوي إدخال وإخراج معًا');
    if (Math.max(qtyIn, qtyOut) > 10000) riskReasons.push('حركة كمية كبيرة جدًا (تحقق مطلوب)');

    const movementType = String(movement.referenceType || movement.reference_type || 'movement').toLowerCase();
    const updatedAt = inferUpdateAt(movement);
    const updatedBy = inferUpdateBy(movement);
    const note = String(movement.note || '').trim();
    let modificationNote = 'تسجيل حركة مخزون';
    let modificationBy = String(movement.createdBy || updatedBy || '-');
    let modificationAt = String(updatedAt || eventDate);
    let isModified = false;

    if (movementType.includes('adjust')) {
      modificationNote = note ? `تسوية مخزون: ${note}` : 'تعديل/تسوية رصيد مخزون';
      isModified = true;
    } else if (updatedAt || updatedBy) {
      modificationNote = note ? `تعديل حركة مخزون: ${note}` : 'تعديل حركة مخزون';
      modificationBy = String(updatedBy || movement.createdBy || '-');
      isModified = true;
    }

    const riskScore = Math.min(100, riskReasons.length * 30);
    const severity: EventSeverity = riskScore >= 70 ? 'high' : riskScore >= 35 ? 'medium' : 'low';

    return {
      id: `inventory:${String(movement.id || '')}`,
      eventDate,
      eventDay: toDay(eventDate),
      source: 'inventory' as const,
      eventType: String(movement.referenceType || movement.reference_type || 'movement'),
      referenceId: String(movement.referenceId || movement.reference_id || movement.id || ''),
      referenceNumber: String(movement.referenceId || movement.reference_id || movement.id || '-'),
      actorName: String(movement.createdBy || '-'),
      amountBase: 0,
      severity,
      riskScore,
      riskReasons,
      modificationNote,
      modificationBy,
      modificationAt,
      isModified,
      preview: `الصنف: ${String(movement.materialId || movement.material_id || '-')} | داخل: ${qtyIn} | خارج: ${qtyOut}`,
    };
  });
}

function filterByDate(events: MonitoringEvent[], fromDay: string, toDay: string): MonitoringEvent[] {
  return events.filter((event) => {
    if (!event.eventDay) return false;
    if (fromDay && event.eventDay < fromDay) return false;
    if (toDay && event.eventDay > toDay) return false;
    return true;
  });
}

function filterBySelects(events: MonitoringEvent[], source: string, severity: string, changeScope: string): MonitoringEvent[] {
  return events.filter((event) => {
    if (source && source !== 'all' && event.source !== source) return false;
    if (severity && severity !== 'all' && event.severity !== severity) return false;
    if (changeScope === 'modified-only' && !event.isModified) return false;
    return true;
  });
}

function sortEvents(events: MonitoringEvent[], key: EventSortKey, direction: SortDirection): MonitoringEvent[] {
  const copy = [...events];
  const severityOrder: Record<EventSeverity, number> = { low: 1, medium: 2, high: 3 };

  copy.sort((a, b) => {
    let result = 0;

    if (key === 'date') {
      result = new Date(a.eventDate).getTime() - new Date(b.eventDate).getTime();
    } else if (key === 'source') {
      result = sourceLabel(a.source).localeCompare(sourceLabel(b.source), 'ar');
    } else if (key === 'type') {
      result = String(a.eventType || '').localeCompare(String(b.eventType || ''), 'ar');
    } else if (key === 'reference') {
      result = String(a.referenceNumber || '').localeCompare(String(b.referenceNumber || ''), 'ar');
    } else if (key === 'note') {
      result = String(a.modificationNote || '').localeCompare(String(b.modificationNote || ''), 'ar');
    } else if (key === 'actor') {
      result = String(a.actorName || '').localeCompare(String(b.actorName || ''), 'ar');
    } else if (key === 'severity') {
      result = severityOrder[a.severity] - severityOrder[b.severity];
    } else if (key === 'score') {
      result = Number(a.riskScore || 0) - Number(b.riskScore || 0);
    } else if (key === 'amount') {
      result = Number(a.amountBase || 0) - Number(b.amountBase || 0);
    }

    return direction === 'asc' ? result : -result;
  });

  return copy;
}

export default async function MonitoringPage({
  searchParams,
}: {
  searchParams?: Promise<{
    day?: string;
    from?: string;
    to?: string;
    source?: string;
    severity?: string;
    changeScope?: string;
    sort?: string;
    dir?: string;
    page?: string;
    pageSize?: string;
  }>;
}) {
  const session = await verifySession();
  const user = session.user;
  const settings = await pgGetSettings();

  const canAccessMonitoring =
    hasEmployeePermission(user, settings, 'admin.monitoring') ||
    hasEmployeePermission(user, settings, 'admin.dashboard');

  if (!user || !canAccessMonitoring) {
    return (
      <DashboardLayout>
        <div className="text-center">
          <h1 className="text-2xl font-bold">غير مصرح</h1>
          <p>لا تملك صلاحية الوصول إلى شاشة المراقبة.</p>
        </div>
      </DashboardLayout>
    );
  }

  const params = (await searchParams) || {};
  const day = toDay(String(params.day || ''));
  const from = toDay(String(params.from || day || ''));
  const to = toDay(String(params.to || day || ''));
  const source = String(params.source || 'all').trim();
  const severity = String(params.severity || 'all').trim();
  const changeScope = String(params.changeScope || 'all').trim();
  const sort = (String(params.sort || 'date').trim() as EventSortKey);
  const dir = (String(params.dir || 'desc').trim() as SortDirection);
  const pageSize = Math.max(10, Math.min(200, Number(params.pageSize || 50) || 50));

  const [invoiceResult, paymentResult, journalResult, movementResult, currencySymbol] = await Promise.all([
    pgGetInvoices({ page: 1, pageSize: 3000 }),
    pgGetPayments({ page: 1, pageSize: 3000 }),
    pgGetJournalEntries({ page: 1, pageSize: 4000 }),
    pgGetInventoryMovements({ page: 1, pageSize: 4000 }),
    getCurrencySymbolAsync(),
  ]);

  const invoiceEvents = buildInvoiceEvents(invoiceResult.items || []);
  const paymentEvents = buildPaymentEvents(paymentResult.items || []);
  const journalEvents = buildJournalEvents(journalResult.items || []);
  const inventoryEvents = buildInventoryEvents(movementResult.items || []);

  const allEvents = [...invoiceEvents, ...paymentEvents, ...journalEvents, ...inventoryEvents]
    .sort((a, b) => new Date(b.eventDate).getTime() - new Date(a.eventDate).getTime());

  const dateFiltered = filterByDate(allEvents, from, to);
  const filteredEvents = filterBySelects(dateFiltered, source, severity, changeScope);
  const events = sortEvents(filteredEvents, sort, dir);

  const totalPages = Math.max(1, Math.ceil(events.length / pageSize));
  const page = Math.max(1, Math.min(totalPages, Number(params.page || 1) || 1));
  const startIndex = (page - 1) * pageSize;
  const pagedEvents = events.slice(startIndex, startIndex + pageSize);

  const baseParams = new URLSearchParams();
  if (day) baseParams.set('day', day);
  if (from) baseParams.set('from', from);
  if (to) baseParams.set('to', to);
  if (source && source !== 'all') baseParams.set('source', source);
  if (severity && severity !== 'all') baseParams.set('severity', severity);
  if (changeScope && changeScope !== 'all') baseParams.set('changeScope', changeScope);
  baseParams.set('pageSize', String(pageSize));

  const createSortHref = (key: EventSortKey) => {
    const nextDir: SortDirection = sort === key && dir === 'asc' ? 'desc' : 'asc';
    const qs = new URLSearchParams(baseParams.toString());
    qs.set('sort', key);
    qs.set('dir', nextDir);
    qs.set('page', '1');
    return `/admin/monitoring?${qs.toString()}`;
  };

  const createPageHref = (targetPage: number) => {
    const qs = new URLSearchParams(baseParams.toString());
    qs.set('sort', sort);
    qs.set('dir', dir);
    qs.set('page', String(targetPage));
    return `/admin/monitoring?${qs.toString()}`;
  };

  const sortIndicator = (key: EventSortKey) => {
    if (sort !== key) return '↕';
    return dir === 'asc' ? '↑' : '↓';
  };

  const highRiskCount = events.filter((entry) => entry.severity === 'high').length;
  const mediumRiskCount = events.filter((entry) => entry.severity === 'medium').length;
  const modifiedOnlyCount = events.filter((entry) => entry.isModified).length;
  const totalAmount = events.reduce((sum, event) => sum + Number(event.amountBase || 0), 0);

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <div>
          <h1 className="text-3xl font-bold">مراقبة النظام</h1>
          <p className="text-muted-foreground mt-1">متابعة كل الحركات الجديدة مع تقييم بصري للأخطاء والخسائر المحتملة.</p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>فلاتر المراقبة</CardTitle>
          </CardHeader>
          <CardContent>
            <form method="get" className="grid grid-cols-1 md:grid-cols-6 gap-3">
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">يوم محدد</label>
                <Input type="date" name="day" defaultValue={day} />
              </div>
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">من تاريخ</label>
                <Input type="date" name="from" defaultValue={from} />
              </div>
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">إلى تاريخ</label>
                <Input type="date" name="to" defaultValue={to} />
              </div>
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">المصدر</label>
                <select name="source" defaultValue={source} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                  <option value="all">الكل</option>
                  <option value="invoice">الفواتير</option>
                  <option value="payment">الدفعات</option>
                  <option value="journal">القيود</option>
                  <option value="inventory">المخزون</option>
                </select>
              </div>
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">مستوى الخطورة</label>
                <select name="severity" defaultValue={severity} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                  <option value="all">الكل</option>
                  <option value="high">عالي</option>
                  <option value="medium">متوسط</option>
                  <option value="low">منخفض</option>
                </select>
              </div>
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">نوع الحركة</label>
                <select name="changeScope" defaultValue={changeScope} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                  <option value="all">الكل</option>
                  <option value="modified-only">المعدلة فقط</option>
                </select>
              </div>
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">حجم الصفحة</label>
                <select name="pageSize" defaultValue={String(pageSize)} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                  <option value="25">25</option>
                  <option value="50">50</option>
                  <option value="100">100</option>
                </select>
              </div>
              <input type="hidden" name="sort" value={sort} />
              <input type="hidden" name="dir" value={dir} />
              <input type="hidden" name="page" value="1" />
              <div className="md:col-span-6 flex justify-end">
                <button type="submit" className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90">
                  تطبيق
                </button>
              </div>
            </form>
          </CardContent>
        </Card>

        <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
          <Card>
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">عدد الأحداث</p>
              <p className="text-2xl font-bold">{events.length}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">السندات المعدلة فقط</p>
              <p className="text-2xl font-bold text-blue-700">{modifiedOnlyCount}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">خطورة عالية</p>
              <p className="text-2xl font-bold text-red-700">{highRiskCount}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">خطورة متوسطة</p>
              <p className="text-2xl font-bold text-amber-700">{mediumRiskCount}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">إجمالي أثر مالي</p>
              <p className="text-2xl font-bold">{formatCurrency(totalAmount, currencySymbol)}</p>
            </CardContent>
          </Card>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>سجل الحركات</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="rounded-md border overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead><a href={createSortHref('date')} className="inline-flex items-center gap-1">التاريخ {sortIndicator('date')}</a></TableHead>
                    <TableHead><a href={createSortHref('source')} className="inline-flex items-center gap-1">المصدر {sortIndicator('source')}</a></TableHead>
                    <TableHead><a href={createSortHref('type')} className="inline-flex items-center gap-1">النوع {sortIndicator('type')}</a></TableHead>
                    <TableHead><a href={createSortHref('reference')} className="inline-flex items-center gap-1">المرجع {sortIndicator('reference')}</a></TableHead>
                    <TableHead><a href={createSortHref('note')} className="inline-flex items-center gap-1">ملاحظة التعديل {sortIndicator('note')}</a></TableHead>
                    <TableHead><a href={createSortHref('actor')} className="inline-flex items-center gap-1">المنفذ {sortIndicator('actor')}</a></TableHead>
                    <TableHead><a href={createSortHref('severity')} className="inline-flex items-center gap-1">الخطورة {sortIndicator('severity')}</a></TableHead>
                    <TableHead><a href={createSortHref('score')} className="inline-flex items-center gap-1">التقييم {sortIndicator('score')}</a></TableHead>
                    <TableHead><a href={createSortHref('amount')} className="inline-flex items-center gap-1">الأثر المالي {sortIndicator('amount')}</a></TableHead>
                    <TableHead>معاينة</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {events.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={10} className="text-center py-8 text-muted-foreground">لا توجد حركات ضمن الفلاتر المحددة.</TableCell>
                    </TableRow>
                  ) : (
                    pagedEvents.map((event) => {
                      const risks = event.riskReasons.length > 0 ? event.riskReasons.join(' | ') : 'لا توجد ملاحظات خطورة';
                      return (
                        <TableRow key={event.id}>
                          <TableCell>{event.eventDay || '-'}</TableCell>
                          <TableCell>{sourceLabel(event.source)}</TableCell>
                          <TableCell>{event.eventType}</TableCell>
                          <TableCell className="font-mono text-xs">{event.referenceNumber}</TableCell>
                          <TableCell className="max-w-[280px] text-xs">{event.modificationNote}</TableCell>
                          <TableCell>{event.actorName || '-'}</TableCell>
                          <TableCell>
                            <Badge className={severityBadgeClass(event.severity)}>{event.severity === 'high' ? 'عالي' : event.severity === 'medium' ? 'متوسط' : 'منخفض'}</Badge>
                          </TableCell>
                          <TableCell>{event.riskScore}/100</TableCell>
                          <TableCell>{formatCurrency(event.amountBase, currencySymbol)}</TableCell>
                          <TableCell>
                            <details className="max-w-[420px]">
                              <summary className="cursor-pointer text-primary">عرض</summary>
                              <div className="mt-2 space-y-1 text-xs leading-5 text-muted-foreground">
                                <div>{event.preview}</div>
                                <div className="text-slate-700">تعديل: {event.modificationNote}</div>
                                <div>المنفذ: {event.modificationBy || '-'} | وقت التعديل: {event.modificationAt ? toDay(event.modificationAt) : '-'}</div>
                                <div className="text-rose-700">{risks}</div>
                                {event.source === 'invoice' && event.referenceId ? (
                                  <a className="underline text-primary" href={`/admin/sales/view/${event.referenceId}`}>فتح المستند</a>
                                ) : null}
                              </div>
                            </details>
                          </TableCell>
                        </TableRow>
                      );
                    })
                  )}
                </TableBody>
              </Table>
            </div>
            <div className="mt-3 flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
              <div className="text-xs text-muted-foreground">
                صفحة {page} من {totalPages} • عرض {pagedEvents.length} من أصل {events.length}
              </div>
              <div className="flex items-center gap-2">
                <a
                  href={createPageHref(Math.max(1, page - 1))}
                  className={`inline-flex items-center justify-center rounded-md border px-3 py-1 text-sm ${page <= 1 ? 'pointer-events-none opacity-50' : 'hover:bg-muted'}`}
                >
                  السابق
                </a>
                <a
                  href={createPageHref(Math.min(totalPages, page + 1))}
                  className={`inline-flex items-center justify-center rounded-md border px-3 py-1 text-sm ${page >= totalPages ? 'pointer-events-none opacity-50' : 'hover:bg-muted'}`}
                >
                  التالي
                </a>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
