"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  ArrowDownToLine,
  BadgeCheck,
  BadgeX,
  Banknote,
  CalendarCheck2,
  CheckCircle2,
  CircleAlert,
  Clock3,
  ExternalLink,
  FileWarning,
  HandCoins,
  HeartHandshake,
  ReceiptText,
  RotateCcw,
  SearchX,
  TrendingDown,
  TrendingUp,
  UsersRound,
  WalletCards,
  XCircle,
  type LucideIcon
} from "lucide-react";
import { useEffect, useMemo, useState, useTransition } from "react";
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  ComposedChart,
  Legend,
  Line,
  LineChart,
  Pie,
  PieChart,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis
} from "recharts";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { formatDate } from "@/lib/dates";
import {
  buildReportAnalytics,
  formatReportAmount,
  formatReportCount,
  REPORT_MONTHS,
  type HistoricalComparison,
  type HistoricalMetricKey,
  type ReconciliationStatus,
  type ReportAnalytics,
  type ReportDataset,
  type ReportFilters,
  type ReportOrphan,
  type ReportPayment,
  type ReportStatusFilter,
  type ReportTransfer
} from "@/lib/report-analytics";
import { cn } from "@/lib/utils";

const COLORS = {
  green: "#15803d",
  greenSoft: "#dcfce7",
  red: "#c2413c",
  redSoft: "#fee2e2",
  amber: "#d97706",
  amberSoft: "#fef3c7",
  teal: "#0f766e",
  tealSoft: "#ccfbf1",
  blue: "#2563eb",
  blueSoft: "#dbeafe",
  gray: "#94a3b8",
  grid: "#e2e8f0",
  inkSoft: "#64748b"
} as const;

const tooltipStyle = {
  direction: "rtl" as const,
  border: `1px solid ${COLORS.grid}`,
  borderRadius: 8,
  background: "#ffffff",
  boxShadow: "0 8px 24px rgba(15, 23, 42, 0.08)",
  fontFamily: "var(--font-noto-kufi-arabic), Tahoma, Arial, sans-serif",
  fontSize: 12
};

const statusFilterLabels: Record<ReportStatusFilter, string> = {
  all: "جميع الحالات",
  payments_paid: "دفعات مدفوعة",
  payments_unpaid: "دفعات غير مدفوعة",
  transfers_completed: "تحويلات مكتملة",
  missing_receipt: "تحويلات بدون إيصال"
};

const historicalMetricMeta: Record<
  HistoricalMetricKey,
  { label: string; shortLabel: string; amount: boolean; color: string }
> = {
  sponsoredOrphans: {
    label: "الأيتام المكفولون",
    shortLabel: "الأيتام",
    amount: false,
    color: COLORS.teal
  },
  newOrphans: {
    label: "الأيتام المضافون",
    shortLabel: "الجدد",
    amount: false,
    color: COLORS.blue
  },
  activeSponsors: {
    label: "المتبرعون النشطون",
    shortLabel: "المتبرعون",
    amount: false,
    color: COLORS.green
  },
  requiredAmount: {
    label: "مبالغ الكفالة المطلوبة",
    shortLabel: "المطلوب",
    amount: true,
    color: COLORS.red
  },
  commitmentAmount: {
    label: "التزامات المتبرعين",
    shortLabel: "الالتزامات",
    amount: true,
    color: COLORS.amber
  },
  paymentAmount: {
    label: "دفعات المتبرعين",
    shortLabel: "الدفعات",
    amount: true,
    color: COLORS.green
  },
  transferAmount: {
    label: "تحويلات الأيتام",
    shortLabel: "التحويلات",
    amount: true,
    color: COLORS.blue
  }
};

const reconciliationMeta: Record<
  ReconciliationStatus,
  { label: string; className: string; icon: LucideIcon }
> = {
  complete: {
    label: "الدفع والتحويل مكتملان",
    className: "border-green-200 bg-green-50 text-green-700",
    icon: CheckCircle2
  },
  payment_missing_transfer: {
    label: "الدفع مكتمل والتحويل مفقود",
    className: "border-amber-200 bg-amber-50 text-amber-700",
    icon: Clock3
  },
  unpaid: {
    label: "دفعة المتبرع غير مدفوعة",
    className: "border-red-200 bg-red-50 text-red-700",
    icon: XCircle
  },
  transfer_exists: {
    label: "يوجد تحويل لليتيم",
    className: "border-blue-200 bg-blue-50 text-blue-700",
    icon: ArrowDownToLine
  }
};

type DrilldownKind = "payments" | "transfers" | "orphans";

type Drilldown = {
  kind: DrilldownKind;
  title: string;
  month?: number;
  paymentStatus?: "paid" | "unpaid";
  receiptStatus?: "with_receipt" | "missing_receipt";
  orphanIds?: string[];
  orphanId?: string;
  sponsorId?: string;
  missingItem?: string;
  coverageCategory?: "full" | "partial" | "uncovered";
};

type Props = {
  dataset: ReportDataset;
  initialFilters: ReportFilters;
  yearOptions: number[];
};

function compactAmount(value: number): string {
  const safeValue = Number.isFinite(value) ? Math.max(0, value) : 0;
  if (safeValue >= 1_000_000) return `${Number((safeValue / 1_000_000).toFixed(1))} م`;
  if (safeValue >= 1_000) return `${Number((safeValue / 1_000).toFixed(0))} ألف`;
  return formatReportCount(safeValue);
}

function formatHistoricalValue(value: number, amountValue: boolean): string {
  return amountValue ? formatReportAmount(value) : formatReportCount(value);
}

function formatSignedValue(value: number, amountValue: boolean): string {
  const sign = value > 0 ? "+" : value < 0 ? "-" : "";
  return `${sign}${formatHistoricalValue(Math.abs(value), amountValue)}`;
}

function formatPercentage(value: number | null): string {
  if (value === null) return "جديد";
  return `${value > 0 ? "+" : ""}${value}%`;
}

function comparisonSummary(
  comparison: HistoricalComparison,
  amountValue: boolean,
  previousLabel: string
): string {
  return `${formatSignedValue(comparison.difference, amountValue)} (${formatPercentage(comparison.percentage)}) مقارنة بـ ${previousLabel}`;
}

function shortLabel(value: string, length = 16): string {
  return value.length > length ? `${value.slice(0, length)}…` : value;
}

function hasChartValues(data: Array<{ value: number }>): boolean {
  return data.some((item) => item.value > 0);
}

function useCompactCharts(): boolean {
  const [compact, setCompact] = useState(false);

  useEffect(() => {
    const media = window.matchMedia("(max-width: 639px)");
    const update = () => setCompact(media.matches);
    update();
    media.addEventListener("change", update);
    return () => media.removeEventListener("change", update);
  }, []);

  return compact;
}

function DashboardSection({
  title,
  description,
  children
}: {
  title: string;
  description: string;
  children: React.ReactNode;
}) {
  return (
    <section className="mt-10 min-w-0">
      <div className="mb-4">
        <h2 className="text-lg font-black leading-8 sm:text-xl">{title}</h2>
        <p className="mt-1 max-w-3xl text-sm leading-7 text-[var(--ink-soft)]">{description}</p>
      </div>
      {children}
    </section>
  );
}

function ChartPanel({
  title,
  note,
  action,
  children,
  className
}: {
  title: string;
  note?: string;
  action?: React.ReactNode;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <Card className={cn("min-w-0 overflow-hidden p-4 sm:p-5", className)}>
      <div className="flex min-w-0 flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div className="min-w-0">
          <h3 className="text-sm font-black leading-7 sm:text-base">{title}</h3>
          {note ? <p className="mt-1 text-xs leading-6 text-[var(--ink-faint)]">{note}</p> : null}
        </div>
        {action}
      </div>
      <div className="mt-4 min-w-0">{children}</div>
    </Card>
  );
}

function ChartEmpty({ title = "لا توجد بيانات ضمن التصفية الحالية" }: { title?: string }) {
  return (
    <div className="grid h-64 place-items-center rounded-md border border-dashed bg-slate-50 px-5 text-center">
      <div>
        <SearchX className="mx-auto text-slate-400" size={28} aria-hidden />
        <p className="mt-3 text-sm font-bold text-[var(--ink-soft)]">{title}</p>
      </div>
    </div>
  );
}

function KpiCard({
  label,
  value,
  note,
  icon: Icon,
  tone
}: {
  label: string;
  value: string;
  note: string;
  icon: LucideIcon;
  tone: "teal" | "green" | "red" | "amber" | "blue";
}) {
  const cardToneClasses = {
    teal: "border-s-teal-600",
    green: "border-s-green-600",
    red: "border-s-red-600",
    amber: "border-s-amber-500",
    blue: "border-s-blue-600"
  };
  const iconToneClasses = {
    teal: "bg-teal-50 text-teal-700",
    green: "bg-green-50 text-green-700",
    red: "bg-red-50 text-red-700",
    amber: "bg-amber-50 text-amber-700",
    blue: "bg-blue-50 text-blue-700"
  };

  return (
    <Card className={cn("min-w-0 border-s-4 p-4 sm:p-5", cardToneClasses[tone])}>
      <div className="flex min-w-0 items-start justify-between gap-3">
        <p className="min-w-0 text-xs font-bold leading-6 text-[var(--ink-soft)] sm:text-sm">{label}</p>
        <span className={cn("grid size-9 shrink-0 place-items-center rounded-md", iconToneClasses[tone])}>
          <Icon size={18} aria-hidden />
        </span>
      </div>
      <p className="mt-3 break-words text-xl font-black leading-8 sm:text-2xl">{value}</p>
      <p className="mt-1 text-xs leading-6 text-[var(--ink-faint)]">{note}</p>
    </Card>
  );
}

function DonutVisual({
  data,
  colors,
  onSelect,
  valueSuffix = "سجل"
}: {
  data: Array<{ key: string; label: string; value: number }>;
  colors: string[];
  onSelect?: (key: string) => void;
  valueSuffix?: string;
}) {
  if (!hasChartValues(data)) return <ChartEmpty />;

  return (
    <div className="h-72 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <PieChart margin={{ top: 4, right: 4, bottom: 28, left: 4 }}>
          <Pie
            data={data}
            dataKey="value"
            nameKey="label"
            cx="50%"
            cy="44%"
            innerRadius="52%"
            outerRadius="76%"
            paddingAngle={2}
            stroke="#ffffff"
            strokeWidth={3}
          >
            {data.map((item, index) => (
              <Cell
                key={item.key}
                fill={colors[index % colors.length]}
                cursor={onSelect ? "pointer" : "default"}
                onClick={() => onSelect?.(item.key)}
              />
            ))}
          </Pie>
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value, name) => [`${formatReportCount(Number(value))} ${valueSuffix}`, String(name)]}
          />
          <Legend
            verticalAlign="bottom"
            iconType="circle"
            wrapperStyle={{ direction: "rtl", fontSize: 11, lineHeight: "22px" }}
          />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
}

function PaymentAmountBars({
  data,
  compact,
  onMonth
}: {
  data: ReportAnalytics["periodMonthly"];
  compact: boolean;
  onMonth: (month: number) => void;
}) {
  if (!data.some((item) => item.expectedAmount > 0 || item.receivedAmount > 0 || item.unpaidAmount > 0)) {
    return <ChartEmpty title="لا توجد التزامات دفع مسجلة في هذه الفترة" />;
  }

  return (
    <div className="h-72 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <BarChart data={data} margin={{ top: 8, right: 4, bottom: 22, left: compact ? 0 : 12 }} accessibilityLayer>
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" vertical={false} />
          <XAxis
            dataKey="monthLabel"
            tickFormatter={(value) => String(value).slice(0, 3)}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 11 }}
            axisLine={false}
            tickLine={false}
            interval={compact && data.length > 6 ? 1 : 0}
          />
          <YAxis
            tickFormatter={compactAmount}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 42 : 62}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value, name) => [formatReportAmount(Number(value)), String(name)]}
            labelFormatter={(label) => `شهر ${label}`}
            cursor={{ fill: "#f8fafc" }}
          />
          <Legend wrapperStyle={{ direction: "rtl", fontSize: 11 }} />
          <Bar dataKey="expectedAmount" name="المتوقع" fill={COLORS.blue} radius={[4, 4, 0, 0]}>
            {data.map((item) => <Cell key={`expected-${item.month}`} onClick={() => onMonth(item.month)} cursor="pointer" />)}
          </Bar>
          <Bar dataKey="receivedAmount" name="المدفوع" fill={COLORS.green} radius={[4, 4, 0, 0]}>
            {data.map((item) => <Cell key={`paid-${item.month}`} onClick={() => onMonth(item.month)} cursor="pointer" />)}
          </Bar>
          <Bar dataKey="unpaidAmount" name="غير المدفوع" fill={COLORS.red} radius={[4, 4, 0, 0]}>
            {data.map((item) => <Cell key={`unpaid-${item.month}`} onClick={() => onMonth(item.month)} cursor="pointer" />)}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

function PaymentTrend({
  data,
  compact
}: {
  data: ReportAnalytics["annualMonthly"];
  compact: boolean;
}) {
  if (!data.some((item) => item.receivedAmount > 0)) return <ChartEmpty title="لا توجد دفعات خلال السنة المحددة" />;

  return (
    <div className="h-72 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart data={data} margin={{ top: 8, right: 8, bottom: 12, left: compact ? 0 : 12 }} accessibilityLayer>
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" vertical={false} />
          <XAxis
            dataKey="monthLabel"
            tickFormatter={(value) => String(value).slice(0, 3)}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 11 }}
            axisLine={false}
            tickLine={false}
            interval={compact ? 1 : 0}
          />
          <YAxis
            tickFormatter={compactAmount}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 42 : 62}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value) => [formatReportAmount(Number(value)), "دفعات المتبرعين"]}
            labelFormatter={(label) => `شهر ${label}`}
          />
          <Line
            type="monotone"
            dataKey="receivedAmount"
            name="دفعات المتبرعين"
            stroke={COLORS.teal}
            strokeWidth={3}
            dot={{ r: 3, fill: COLORS.teal, strokeWidth: 0 }}
            activeDot={{ r: 5 }}
          />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

function TransferMonthBars({
  data,
  compact,
  onMonth
}: {
  data: ReportAnalytics["periodMonthly"];
  compact: boolean;
  onMonth: (month: number) => void;
}) {
  if (!data.some((item) => item.transferAmount > 0)) return <ChartEmpty title="لا توجد تحويلات في هذه الفترة" />;

  return (
    <div className="h-72 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <BarChart data={data} margin={{ top: 8, right: 4, bottom: 12, left: compact ? 0 : 12 }} accessibilityLayer>
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" vertical={false} />
          <XAxis
            dataKey="monthLabel"
            tickFormatter={(value) => String(value).slice(0, 3)}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 11 }}
            axisLine={false}
            tickLine={false}
            interval={compact && data.length > 6 ? 1 : 0}
          />
          <YAxis
            tickFormatter={compactAmount}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 42 : 62}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value) => [formatReportAmount(Number(value)), "تحويلات الأيتام"]}
            labelFormatter={(label) => `شهر ${label}`}
            cursor={{ fill: "#f8fafc" }}
          />
          <Bar dataKey="transferAmount" name="تحويلات الأيتام" fill={COLORS.blue} radius={[4, 4, 0, 0]}>
            {data.map((item) => <Cell key={item.month} onClick={() => onMonth(item.month)} cursor="pointer" />)}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

function HorizontalValueBars({
  data,
  compact,
  amountValues = false,
  color = COLORS.teal,
  onSelect
}: {
  data: Array<{ id?: string; label: string; value: number }>;
  compact: boolean;
  amountValues?: boolean;
  color?: string;
  onSelect?: (item: { id?: string; label: string; value: number }) => void;
}) {
  const visible = data.slice(0, 12);
  if (!hasChartValues(visible)) return <ChartEmpty />;
  const chartHeight = Math.max(260, visible.length * (compact ? 38 : 42));

  return (
    <div className="min-w-0" style={{ height: chartHeight }} dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <BarChart
          data={visible}
          layout="vertical"
          margin={{ top: 4, right: compact ? 8 : 20, bottom: 8, left: 2 }}
          accessibilityLayer
        >
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" horizontal={false} />
          <XAxis
            type="number"
            tickFormatter={amountValues ? compactAmount : formatReportCount}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
          />
          <YAxis
            type="category"
            dataKey="label"
            orientation="left"
            width={compact ? 92 : 132}
            tickFormatter={(value) => shortLabel(String(value), compact ? 12 : 18)}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value) => [
              amountValues ? formatReportAmount(Number(value)) : formatReportCount(Number(value)),
              amountValues ? "المبلغ" : "العدد"
            ]}
            labelFormatter={(label) => String(label)}
            cursor={{ fill: "#f8fafc" }}
          />
          <Bar dataKey="value" fill={color} radius={[0, 4, 4, 0]}>
            {visible.map((item, index) => (
              <Cell
                key={item.id ?? `${item.label}-${index}`}
                cursor={onSelect ? "pointer" : "default"}
                onClick={() => onSelect?.(item)}
              />
            ))}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

function AnnualAreaChart({
  data,
  compact
}: {
  data: ReportAnalytics["annualMonthly"];
  compact: boolean;
}) {
  if (!data.some((item) => item.receivedAmount > 0 || item.transferAmount > 0)) {
    return <ChartEmpty title="لا توجد حركة مالية سنوية لعرضها" />;
  }

  return (
    <div className="h-80 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <AreaChart data={data} margin={{ top: 8, right: 8, bottom: 12, left: compact ? 0 : 12 }} accessibilityLayer>
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" vertical={false} />
          <XAxis
            dataKey="monthLabel"
            tickFormatter={(value) => String(value).slice(0, 3)}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 11 }}
            axisLine={false}
            tickLine={false}
            interval={compact ? 1 : 0}
          />
          <YAxis
            tickFormatter={compactAmount}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 42 : 62}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value, name) => [formatReportAmount(Number(value)), String(name)]}
            labelFormatter={(label) => `شهر ${label}`}
          />
          <Legend wrapperStyle={{ direction: "rtl", fontSize: 11 }} />
          <Area
            type="monotone"
            dataKey="receivedAmount"
            name="دفعات المتبرعين"
            stroke={COLORS.green}
            fill={COLORS.greenSoft}
            fillOpacity={0.65}
            strokeWidth={2}
          />
          <Area
            type="monotone"
            dataKey="transferAmount"
            name="تحويلات الأيتام"
            stroke={COLORS.blue}
            fill={COLORS.blueSoft}
            fillOpacity={0.55}
            strokeWidth={2}
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}

function SponsorCountBars({
  data,
  compact
}: {
  data: ReportAnalytics["annualMonthly"];
  compact: boolean;
}) {
  if (!data.some((item) => item.paidSponsors > 0 || item.unpaidSponsors > 0)) {
    return <ChartEmpty title="لا توجد حالات دفع شهرية خلال السنة" />;
  }

  return (
    <div className="h-80 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <BarChart data={data} margin={{ top: 8, right: 4, bottom: 12, left: 0 }} accessibilityLayer>
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" vertical={false} />
          <XAxis
            dataKey="monthLabel"
            tickFormatter={(value) => String(value).slice(0, 3)}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 11 }}
            axisLine={false}
            tickLine={false}
            interval={compact ? 1 : 0}
          />
          <YAxis
            allowDecimals={false}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 24 : 34}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value, name) => [formatReportCount(Number(value)), String(name)]}
            labelFormatter={(label) => `شهر ${label}`}
            cursor={{ fill: "#f8fafc" }}
          />
          <Legend wrapperStyle={{ direction: "rtl", fontSize: 11 }} />
          <Bar dataKey="paidSponsors" name="متبرعون دفعوا" stackId="sponsors" fill={COLORS.green} />
          <Bar dataKey="unpaidSponsors" name="متبرعون لم يدفعوا" stackId="sponsors" fill={COLORS.red} radius={[4, 4, 0, 0]} />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

function ChangeIndicator({
  label,
  value,
  month
}: {
  label: string;
  value: number | null;
  month: number;
}) {
  const positive = value !== null && value >= 0;
  const Icon = positive ? TrendingUp : TrendingDown;

  return (
    <div className="min-w-0 rounded-lg border bg-white p-4">
      <p className="text-xs font-bold leading-6 text-[var(--ink-soft)]">{label}</p>
      <div className="mt-2 flex items-center gap-2">
        {value === null ? (
          <span className="text-lg font-black text-[var(--ink-faint)]">لا توجد مقارنة</span>
        ) : (
          <>
            <Icon size={20} className={positive ? "text-green-700" : "text-red-700"} aria-hidden />
            <strong className={cn("text-xl", positive ? "text-green-700" : "text-red-700")}>
              {value > 0 ? "+" : ""}{value}%
            </strong>
          </>
        )}
      </div>
      <p className="mt-1 text-xs text-[var(--ink-faint)]">مقارنة {REPORT_MONTHS[month - 1]} بالشهر السابق</p>
    </div>
  );
}

function TrendBadge({
  comparison,
  amountValue = false
}: {
  comparison: HistoricalComparison;
  amountValue?: boolean;
}) {
  const positive = comparison.difference > 0;
  const negative = comparison.difference < 0;
  const Icon = negative ? TrendingDown : TrendingUp;

  return (
    <span
      className={cn(
        "inline-flex min-h-8 items-center gap-1 rounded-md border px-2 py-1 text-[11px] font-black",
        positive && "border-green-200 bg-green-50 text-green-700",
        negative && "border-red-200 bg-red-50 text-red-700",
        !positive && !negative && "border-slate-200 bg-slate-50 text-slate-600"
      )}
    >
      {comparison.difference === 0 ? null : <Icon size={13} aria-hidden />}
      <span>{formatSignedValue(comparison.difference, amountValue)}</span>
      <span className="font-bold">({formatPercentage(comparison.percentage)})</span>
    </span>
  );
}

function HistoricalEntityTrend({
  data,
  compact,
  selectedMonth
}: {
  data: ReportAnalytics["history"]["monthly"];
  compact: boolean;
  selectedMonth: number;
}) {
  if (!data.length) return <ChartEmpty title="لا توجد لقطات شهرية محفوظة لهذه السنة" />;

  return (
    <div className="h-80 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart data={data} margin={{ top: 8, right: 8, bottom: 12, left: 0 }} accessibilityLayer>
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" vertical={false} />
          <XAxis
            dataKey="monthLabel"
            tickFormatter={(value) => String(value).slice(0, 3)}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 11 }}
            axisLine={false}
            tickLine={false}
            interval={compact ? 1 : 0}
          />
          <YAxis
            allowDecimals={false}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 24 : 34}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value, name) => [formatReportCount(Number(value)), String(name)]}
            labelFormatter={(label) => `شهر ${label}`}
          />
          <Legend wrapperStyle={{ direction: "rtl", fontSize: 11 }} />
          <ReferenceLine
            x={REPORT_MONTHS[selectedMonth - 1]}
            stroke={COLORS.amber}
            strokeDasharray="4 4"
          />
          <Line
            type="monotone"
            dataKey="sponsoredOrphans"
            name="الأيتام المكفولون"
            stroke={COLORS.teal}
            strokeWidth={3}
            dot={{ r: 3, fill: COLORS.teal, strokeWidth: 0 }}
          />
          <Line
            type="monotone"
            dataKey="activeSponsors"
            name="المتبرعون النشطون"
            stroke={COLORS.green}
            strokeWidth={2}
            dot={{ r: 3, fill: COLORS.green, strokeWidth: 0 }}
          />
          <Line
            type="monotone"
            dataKey="newOrphans"
            name="الأيتام الجدد"
            stroke={COLORS.blue}
            strokeWidth={2}
            strokeDasharray="5 4"
            dot={{ r: 3, fill: COLORS.blue, strokeWidth: 0 }}
          />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

function HistoricalCommitmentBars({
  data,
  compact,
  selectedMonth
}: {
  data: ReportAnalytics["history"]["monthly"];
  compact: boolean;
  selectedMonth: number;
}) {
  if (!data.length) return <ChartEmpty title="لا توجد التزامات تاريخية محفوظة لهذه السنة" />;

  return (
    <div className="h-80 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <BarChart data={data} margin={{ top: 8, right: 4, bottom: 12, left: 0 }} accessibilityLayer>
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" vertical={false} />
          <XAxis
            dataKey="monthLabel"
            tickFormatter={(value) => String(value).slice(0, 3)}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 11 }}
            axisLine={false}
            tickLine={false}
            interval={compact ? 1 : 0}
          />
          <YAxis
            tickFormatter={compactAmount}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 42 : 62}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value, name) => [formatReportAmount(Number(value)), String(name)]}
            labelFormatter={(label) => `شهر ${label}`}
            cursor={{ fill: "#f8fafc" }}
          />
          <Legend wrapperStyle={{ direction: "rtl", fontSize: 11 }} />
          <ReferenceLine
            x={REPORT_MONTHS[selectedMonth - 1]}
            stroke={COLORS.amber}
            strokeDasharray="4 4"
          />
          <Bar
            dataKey="requiredAmount"
            name="المبلغ المطلوب"
            fill={COLORS.blue}
            radius={[4, 4, 0, 0]}
          />
          <Bar
            dataKey="commitmentAmount"
            name="التزامات المتبرعين"
            fill={COLORS.amber}
            radius={[4, 4, 0, 0]}
          />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

function HistoricalFinancialArea({
  data,
  compact,
  selectedMonth
}: {
  data: ReportAnalytics["history"]["monthly"];
  compact: boolean;
  selectedMonth: number;
}) {
  if (!data.length) return <ChartEmpty title="لا توجد حركة مالية تاريخية لهذه السنة" />;

  return (
    <div className="h-80 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <AreaChart data={data} margin={{ top: 8, right: 8, bottom: 12, left: 0 }} accessibilityLayer>
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" vertical={false} />
          <XAxis
            dataKey="monthLabel"
            tickFormatter={(value) => String(value).slice(0, 3)}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 11 }}
            axisLine={false}
            tickLine={false}
            interval={compact ? 1 : 0}
          />
          <YAxis
            tickFormatter={compactAmount}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 42 : 62}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value, name) => [formatReportAmount(Number(value)), String(name)]}
            labelFormatter={(label) => `شهر ${label}`}
          />
          <Legend wrapperStyle={{ direction: "rtl", fontSize: 11 }} />
          <ReferenceLine
            x={REPORT_MONTHS[selectedMonth - 1]}
            stroke={COLORS.amber}
            strokeDasharray="4 4"
          />
          <Area
            type="monotone"
            dataKey="paymentAmount"
            name="دفعات المتبرعين"
            stroke={COLORS.green}
            fill={COLORS.greenSoft}
            fillOpacity={0.7}
            strokeWidth={2}
          />
          <Area
            type="monotone"
            dataKey="transferAmount"
            name="تحويلات الأيتام"
            stroke={COLORS.blue}
            fill={COLORS.blueSoft}
            fillOpacity={0.55}
            strokeWidth={2}
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}

function HistoricalAnnualGrowth({
  data,
  compact
}: {
  data: ReportAnalytics["history"]["annual"];
  compact: boolean;
}) {
  if (!data.length) return <ChartEmpty title="لا توجد سنوات محفوظة للمقارنة" />;

  return (
    <div className="h-80 min-w-0" dir="ltr">
      <ResponsiveContainer width="100%" height="100%">
        <ComposedChart data={data} margin={{ top: 8, right: 0, bottom: 12, left: 0 }} accessibilityLayer>
          <CartesianGrid stroke={COLORS.grid} strokeDasharray="3 3" vertical={false} />
          <XAxis
            dataKey="yearLabel"
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 9 : 11 }}
            axisLine={false}
            tickLine={false}
          />
          <YAxis
            yAxisId="amount"
            tickFormatter={compactAmount}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 8 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 42 : 62}
          />
          <YAxis
            yAxisId="count"
            orientation="right"
            allowDecimals={false}
            tick={{ fill: COLORS.inkSoft, fontSize: compact ? 8 : 10 }}
            axisLine={false}
            tickLine={false}
            width={compact ? 24 : 34}
          />
          <Tooltip
            contentStyle={tooltipStyle}
            formatter={(value, name, item) => [
              item.dataKey === "paymentAmount" || item.dataKey === "transferAmount"
                ? formatReportAmount(Number(value))
                : formatReportCount(Number(value)),
              String(name)
            ]}
            labelFormatter={(label) => `عام ${label}`}
          />
          <Legend wrapperStyle={{ direction: "rtl", fontSize: 11 }} />
          <Bar
            yAxisId="amount"
            dataKey="paymentAmount"
            name="دفعات المتبرعين"
            fill={COLORS.green}
            radius={[4, 4, 0, 0]}
          />
          <Bar
            yAxisId="amount"
            dataKey="transferAmount"
            name="تحويلات الأيتام"
            fill={COLORS.blue}
            radius={[4, 4, 0, 0]}
          />
          <Line
            yAxisId="count"
            type="monotone"
            dataKey="sponsoredOrphans"
            name="الأيتام المكفولون"
            stroke={COLORS.teal}
            strokeWidth={3}
            dot={{ r: 4, fill: COLORS.teal, strokeWidth: 0 }}
          />
          <Line
            yAxisId="count"
            type="monotone"
            dataKey="activeSponsors"
            name="المتبرعون النشطون"
            stroke={COLORS.amber}
            strokeWidth={2}
            dot={{ r: 4, fill: COLORS.amber, strokeWidth: 0 }}
          />
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  );
}

function MonthlyComparisonCards({
  rows,
  metric
}: {
  rows: ReportAnalytics["history"]["monthlyComparisons"];
  metric: HistoricalMetricKey;
}) {
  const meta = historicalMetricMeta[metric];
  if (!rows.length) return <ChartEmpty title="لا توجد أشهر محفوظة للمقارنة" />;

  return (
    <div className="grid min-w-0 gap-3 sm:grid-cols-2 xl:grid-cols-3">
      {rows.map(({ point, previous, comparisons }) => (
        <article
          key={`${point.year}-${point.month}`}
          className="min-w-0 rounded-md border bg-slate-50 p-3"
        >
          <div className="flex min-w-0 items-start justify-between gap-3">
            <div className="min-w-0">
              <p className="text-xs font-bold text-[var(--ink-soft)]">
                {point.monthLabel} {point.year}
              </p>
              <p className="mt-2 break-words text-lg font-black">
                {formatHistoricalValue(point[metric], meta.amount)}
              </p>
            </div>
            <TrendBadge comparison={comparisons[metric]} amountValue={meta.amount} />
          </div>
          <p className="mt-2 text-[11px] leading-5 text-[var(--ink-faint)]">
            مقابل {previous.monthLabel} {previous.year}:{" "}
            {formatHistoricalValue(previous[metric], meta.amount)}
          </p>
        </article>
      ))}
    </div>
  );
}

export function AnalyticsDashboard({ dataset, initialFilters, yearOptions }: Props) {
  const router = useRouter();
  const [isYearPending, startYearTransition] = useTransition();
  const [filters, setFilters] = useState(initialFilters);
  const [transferGrouping, setTransferGrouping] = useState<"sponsor" | "orphan">("sponsor");
  const [historyMetric, setHistoryMetric] = useState<HistoricalMetricKey>("paymentAmount");
  const [drilldown, setDrilldown] = useState<Drilldown>({
    kind: "payments",
    title: "تفاصيل دفعات المتبرعين"
  });
  const [detailLimit, setDetailLimit] = useState(50);
  const compact = useCompactCharts();
  const analytics = useMemo(() => buildReportAnalytics(dataset, filters), [dataset, filters]);

  const availableOrphans = useMemo(() => {
    if (!filters.sponsorId) return dataset.orphans;
    const ids = new Set(
      dataset.sponsorships
        .filter((item) => item.sponsorId === filters.sponsorId)
        .map((item) => item.orphanId)
    );
    return dataset.orphans.filter((item) => ids.has(item.id));
  }, [dataset.orphans, dataset.sponsorships, filters.sponsorId]);

  useEffect(() => {
    const query = new URLSearchParams({ year: String(dataset.year) });
    if (filters.month) query.set("month", String(filters.month));
    if (filters.sponsorId) query.set("sponsor", filters.sponsorId);
    if (filters.orphanId) query.set("orphan", filters.orphanId);
    if (filters.status !== "all") query.set("status", filters.status);
    window.history.replaceState(window.history.state, "", `/admin/reports?${query.toString()}`);
  }, [dataset.year, filters]);

  function changeYear(nextYear: number) {
    const query = new URLSearchParams({ year: String(nextYear) });
    if (filters.month) query.set("month", String(filters.month));
    if (filters.sponsorId) query.set("sponsor", filters.sponsorId);
    if (filters.orphanId) query.set("orphan", filters.orphanId);
    if (filters.status !== "all") query.set("status", filters.status);
    startYearTransition(() => router.push(`/admin/reports?${query.toString()}`));
  }

  function changeSponsor(sponsorId: string | null) {
    const linkedOrphans =
      sponsorId === null
        ? null
        : new Set(
            dataset.sponsorships
              .filter((item) => item.sponsorId === sponsorId)
              .map((item) => item.orphanId)
          );
    setFilters((current) => ({
      ...current,
      sponsorId,
      orphanId:
        current.orphanId && linkedOrphans && !linkedOrphans.has(current.orphanId)
          ? null
          : current.orphanId
    }));
  }

  function resetFilters() {
    setFilters({ month: null, sponsorId: null, orphanId: null, status: "all" });
  }

  function openDrilldown(next: Drilldown) {
    setDrilldown(next);
    setDetailLimit(50);
    window.requestAnimationFrame(() => {
      document.getElementById("report-details")?.scrollIntoView({ behavior: "smooth", block: "start" });
    });
  }

  const historyPreviousLabel = `${analytics.history.previous.monthLabel} ${analytics.history.previous.year}`;
  const historyPaymentComparison = analytics.history.comparisons.paymentAmount;
  const historyKpis = [
    {
      label: "الأيتام المكفولون هذا الشهر",
      value: formatReportCount(analytics.history.current.sponsoredOrphans),
      note: comparisonSummary(
        analytics.history.comparisons.sponsoredOrphans,
        false,
        historyPreviousLabel
      ),
      icon: HeartHandshake,
      tone: "teal" as const
    },
    {
      label: "الأيتام المضافون هذا الشهر",
      value: formatReportCount(analytics.history.current.newOrphans),
      note: comparisonSummary(
        analytics.history.comparisons.newOrphans,
        false,
        historyPreviousLabel
      ),
      icon: UsersRound,
      tone: "blue" as const
    },
    {
      label: "المتبرعون النشطون هذا الشهر",
      value: formatReportCount(analytics.history.current.activeSponsors),
      note: comparisonSummary(
        analytics.history.comparisons.activeSponsors,
        false,
        historyPreviousLabel
      ),
      icon: BadgeCheck,
      tone: "green" as const
    },
    {
      label: "مبالغ الكفالة المطلوبة",
      value: formatReportAmount(analytics.history.current.requiredAmount),
      note: comparisonSummary(
        analytics.history.comparisons.requiredAmount,
        true,
        historyPreviousLabel
      ),
      icon: Banknote,
      tone: "blue" as const
    },
    {
      label: "التزامات المتبرعين",
      value: formatReportAmount(analytics.history.current.commitmentAmount),
      note: comparisonSummary(
        analytics.history.comparisons.commitmentAmount,
        true,
        historyPreviousLabel
      ),
      icon: CalendarCheck2,
      tone: "amber" as const
    },
    {
      label: "دفعات المتبرعين هذا الشهر",
      value: formatReportAmount(analytics.history.current.paymentAmount),
      note: comparisonSummary(historyPaymentComparison, true, historyPreviousLabel),
      icon: WalletCards,
      tone: "green" as const
    },
    {
      label: "تحويلات الأيتام هذا الشهر",
      value: formatReportAmount(analytics.history.current.transferAmount),
      note: comparisonSummary(
        analytics.history.comparisons.transferAmount,
        true,
        historyPreviousLabel
      ),
      icon: HandCoins,
      tone: "teal" as const
    },
    {
      label: "فرق الدفعات عن الشهر السابق",
      value: formatSignedValue(historyPaymentComparison.difference, true),
      note: `قيمة الشهر السابق: ${formatReportAmount(historyPaymentComparison.previous)}`,
      icon: historyPaymentComparison.difference < 0 ? TrendingDown : TrendingUp,
      tone: historyPaymentComparison.difference < 0 ? ("red" as const) : ("green" as const)
    },
    {
      label: "نسبة نمو أو تراجع الدفعات",
      value: formatPercentage(historyPaymentComparison.percentage),
      note: `مقارنة ${analytics.history.current.monthLabel} بـ ${historyPreviousLabel}`,
      icon: historyPaymentComparison.difference < 0 ? TrendingDown : TrendingUp,
      tone: historyPaymentComparison.difference < 0 ? ("red" as const) : ("green" as const)
    }
  ];

  const kpis = [
    {
      label: "إجمالي المبالغ المتوقعة",
      value: formatReportAmount(analytics.kpis.expectedAmount),
      note: "التزامات الفترة المحددة",
      icon: CalendarCheck2,
      tone: "blue" as const
    },
    {
      label: "إجمالي دفعات المتبرعين",
      value: formatReportAmount(analytics.kpis.receivedAmount),
      note: "المبالغ المستلمة فعلياً",
      icon: WalletCards,
      tone: "green" as const
    },
    {
      label: "إجمالي المبالغ غير المدفوعة",
      value: formatReportAmount(analytics.kpis.unpaidAmount),
      note: "المتوقع ناقص المستلم",
      icon: CircleAlert,
      tone: "red" as const
    },
    {
      label: "إجمالي تحويلات الأيتام",
      value: formatReportAmount(analytics.kpis.transferAmount),
      note: "تحويلات فريدة غير مكررة",
      icon: HandCoins,
      tone: "teal" as const
    },
    {
      label: "عدد المتبرعين الذين دفعوا",
      value: formatReportCount(analytics.kpis.paidSponsors),
      note: "اكتملت كل دفعاتهم في الفترة",
      icon: BadgeCheck,
      tone: "green" as const
    },
    {
      label: "عدد المتبرعين الذين لم يدفعوا",
      value: formatReportCount(analytics.kpis.unpaidSponsors),
      note: "لديهم دفعة واحدة غير مدفوعة على الأقل",
      icon: BadgeX,
      tone: "red" as const
    },
    {
      label: "عدد الحالات النشطة",
      value: formatReportCount(analytics.kpis.activeCases),
      note: "غير موقوفة أو مؤرشفة",
      icon: UsersRound,
      tone: "blue" as const
    },
    {
      label: "التحويلات بدون إيصالات",
      value: formatReportCount(analytics.kpis.missingReceipts),
      note: "تحتاج إلى توثيق",
      icon: ReceiptText,
      tone: "amber" as const
    }
  ];

  return (
    <div className="min-w-0">
      <Card className={cn("p-4 sm:p-5", isYearPending && "opacity-60")} aria-busy={isYearPending}>
        <div className="grid min-w-0 gap-4 sm:grid-cols-2 xl:grid-cols-5">
          <FilterSelect
            label="السنة"
            value={String(dataset.year)}
            onChange={(value) => changeYear(Number(value))}
            options={yearOptions.map((value) => ({ value: String(value), label: String(value) }))}
          />
          <FilterSelect
            label="الشهر"
            value={filters.month ? String(filters.month) : ""}
            onChange={(value) => setFilters((current) => ({ ...current, month: value ? Number(value) : null }))}
            options={[
              { value: "", label: "السنة كاملة" },
              ...REPORT_MONTHS.map((label, index) => ({ value: String(index + 1), label }))
            ]}
          />
          <FilterSelect
            label="المتبرع"
            value={filters.sponsorId ?? ""}
            onChange={(value) => changeSponsor(value || null)}
            options={[
              { value: "", label: "جميع المتبرعين" },
              ...dataset.sponsors.map((item) => ({ value: item.id, label: item.name }))
            ]}
          />
          <FilterSelect
            label="اليتيم"
            value={filters.orphanId ?? ""}
            onChange={(value) => setFilters((current) => ({ ...current, orphanId: value || null }))}
            options={[
              { value: "", label: "جميع الحالات" },
              ...availableOrphans.map((item) => ({
                value: item.id,
                label: `${item.name} - ${item.caseNumber}`
              }))
            ]}
          />
          <FilterSelect
            label="الحالة"
            value={filters.status}
            onChange={(value) => setFilters((current) => ({ ...current, status: value as ReportStatusFilter }))}
            options={Object.entries(statusFilterLabels).map(([value, label]) => ({ value, label }))}
          />
        </div>
        <div className="mt-4 flex flex-col gap-3 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
          <p className="text-xs leading-6 text-[var(--ink-faint)]">
            الأرقام والرسوم محسوبة من السجلات المطابقة للفلاتر الحالية.
          </p>
          <button
            type="button"
            onClick={resetFilters}
            className="inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-md border bg-white px-4 text-sm font-bold hover:bg-slate-50 sm:w-auto"
          >
            <RotateCcw size={16} aria-hidden />
            إعادة ضبط
          </button>
        </div>
      </Card>

      <div className="mt-5 grid min-w-0 gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {kpis.map((item) => <KpiCard key={item.label} {...item} />)}
      </div>

      <DashboardSection
        title={`السجل التاريخي الشهري - ${analytics.history.current.monthLabel} ${analytics.history.current.year}`}
        description="لقطة شهرية ثابتة مبنية على تواريخ بداية ونهاية الكفالات. تبقى الأشهر المغلقة كما كانت، وتُقارن كل قيمة بالشهر السابق مباشرة."
      >
        {!analytics.history.current.captured ? (
          <div className="mb-4 rounded-md border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-bold leading-7 text-amber-800">
            لا توجد لقطة محفوظة لهذه الفترة؛ القيم التاريخية المعروضة تساوي صفراً حتى تتوفر فترة فعلية.
          </div>
        ) : null}

        <div className="grid min-w-0 gap-3 sm:grid-cols-2 xl:grid-cols-3">
          {historyKpis.map((item) => <KpiCard key={item.label} {...item} />)}
        </div>

        <div className="mt-4 grid min-w-0 gap-4 xl:grid-cols-2">
          <ChartPanel
            title={`نمو الأيتام والمتبرعين خلال ${dataset.year}`}
            note="الأعداد مأخوذة من لقطة كل شهر، والخط المتقطع يوضح الأيتام المضافين حديثاً."
          >
            <HistoricalEntityTrend
              data={analytics.history.monthly}
              compact={compact}
              selectedMonth={analytics.history.selectedMonth}
            />
          </ChartPanel>
          <ChartPanel
            title="المطلوب مقابل التزامات المتبرعين"
            note="الاحتياج الشهري للأيتام المكفولين مقارنة بمجموع مبالغ الكفالات الفعالة في الشهر."
          >
            <HistoricalCommitmentBars
              data={analytics.history.monthly}
              compact={compact}
              selectedMonth={analytics.history.selectedMonth}
            />
          </ChartPanel>
          <ChartPanel
            title="دفعات المتبرعين مقابل تحويلات الأيتام"
            note="القيم الفعلية من سجلي الدفعات والتحويلات الأصليين؛ لا يتم دمج النظامين."
          >
            <HistoricalFinancialArea
              data={analytics.history.monthly}
              compact={compact}
              selectedMonth={analytics.history.selectedMonth}
            />
          </ChartPanel>
          <ChartPanel
            title="النمو عبر السنوات"
            note="الأعمدة للإجماليات المالية السنوية، والخطوط لأعداد الأيتام المكفولين والمتبرعين النشطين في آخر شهر محفوظ."
          >
            <HistoricalAnnualGrowth data={analytics.history.annual} compact={compact} />
          </ChartPanel>
        </div>

        <ChartPanel
          className="mt-4"
          title="مقارنة كل شهر بالشهر السابق"
          note="اختر المؤشر لعرض القيمة، الفرق الرقمي، ونسبة الزيادة أو التراجع لكل شهر محفوظ."
          action={
            <label className="w-full sm:w-56">
              <span className="sr-only">مؤشر المقارنة الشهرية</span>
              <select
                value={historyMetric}
                onChange={(event) => setHistoryMetric(event.target.value as HistoricalMetricKey)}
                className="h-11 w-full rounded-md border bg-white px-3 text-sm font-bold outline-none focus:border-[var(--primary)] focus:ring-4 focus:ring-[var(--focus)]"
              >
                {(Object.entries(historicalMetricMeta) as Array<
                  [HistoricalMetricKey, (typeof historicalMetricMeta)[HistoricalMetricKey]]
                >).map(([key, meta]) => (
                  <option key={key} value={key}>{meta.label}</option>
                ))}
              </select>
            </label>
          }
        >
          <MonthlyComparisonCards
            rows={analytics.history.monthlyComparisons}
            metric={historyMetric}
          />
        </ChartPanel>
      </DashboardSection>

      <DashboardSection
        title="دفعات المتبرعين الشهرية"
        description="مقارنة الالتزامات والمبالغ المستلمة وغير المدفوعة، مع اتجاه الدفعات خلال السنة."
      >
        <div className="grid min-w-0 gap-4 xl:grid-cols-2">
          <ChartPanel title="الدفعات المدفوعة وغير المدفوعة" note="عدد سجلات الالتزام؛ لا توجد حالة دفع جزئي في هذا التقرير.">
            <DonutVisual
              data={analytics.paymentStatus}
              colors={[COLORS.green, COLORS.red]}
              valueSuffix="دفعة"
              onSelect={(key) =>
                openDrilldown({
                  kind: "payments",
                  title: key === "paid" ? "الدفعات المدفوعة" : "الدفعات غير المدفوعة",
                  paymentStatus: key as "paid" | "unpaid"
                })
              }
            />
          </ChartPanel>
          <ChartPanel title="المتوقع والمدفوع وغير المدفوع" note="المبالغ حسب الفترة المحددة.">
            <PaymentAmountBars
              data={analytics.periodMonthly}
              compact={compact}
              onMonth={(month) => openDrilldown({ kind: "payments", title: `دفعات ${REPORT_MONTHS[month - 1]}`, month })}
            />
          </ChartPanel>
        </div>
        <ChartPanel className="mt-4" title="اتجاه دفعات المتبرعين خلال السنة" note={`القيمة الشهرية الفعلية لعام ${dataset.year}.`}>
          <PaymentTrend data={analytics.annualMonthly} compact={compact} />
        </ChartPanel>
      </DashboardSection>

      <DashboardSection
        title="تحويلات الأيتام"
        description="قيمة التحويلات شهرياً، تغطية الحالات بالتحويل، وعدد التحويلات المرتبطة بكل متبرع أو يتيم."
      >
        <div className="grid min-w-0 gap-4 xl:grid-cols-2">
          <ChartPanel title="قيمة التحويلات حسب الشهر" note="كل تحويل مشترك محتسب مرة مالية واحدة.">
            <TransferMonthBars
              data={analytics.periodMonthly}
              compact={compact}
              onMonth={(month) => openDrilldown({ kind: "transfers", title: `تحويلات ${REPORT_MONTHS[month - 1]}`, month })}
            />
          </ChartPanel>
          <ChartPanel title="الحالات المحولة وغير المحولة" note="عدد حالات الأيتام ضمن التصفية الحالية.">
            <DonutVisual
              data={analytics.transferCoverage}
              colors={[COLORS.blue, COLORS.red]}
              valueSuffix="حالة"
              onSelect={(key) => {
                const transferred = new Set(analytics.transfers.map((item) => item.orphanId));
                const orphanIds = analytics.orphans
                  .filter((item) => key === "transferred" ? transferred.has(item.id) : !transferred.has(item.id))
                  .map((item) => item.id);
                openDrilldown({
                  kind: "orphans",
                  title: key === "transferred" ? "الحالات التي لديها تحويل" : "الحالات بدون تحويل",
                  orphanIds
                });
              }}
            />
          </ChartPanel>
        </div>
        <ChartPanel
          className="mt-4"
          title={transferGrouping === "sponsor" ? "التحويلات المرتبطة بكل متبرع" : "التحويلات حسب اليتيم"}
          note={transferGrouping === "sponsor" ? "العدد ارتباطي؛ التحويل المشترك يظهر لدى كل متبرع مرتبط." : "عدد سجلات التحويل الفريدة لكل يتيم."}
          action={
            <div className="grid grid-cols-2 rounded-md border bg-slate-50 p-1" aria-label="تجميع التحويلات">
              <button
                type="button"
                onClick={() => setTransferGrouping("sponsor")}
                className={cn("min-h-9 rounded px-3 text-xs font-bold", transferGrouping === "sponsor" && "bg-white text-[var(--primary)] shadow-sm")}
              >
                حسب المتبرع
              </button>
              <button
                type="button"
                onClick={() => setTransferGrouping("orphan")}
                className={cn("min-h-9 rounded px-3 text-xs font-bold", transferGrouping === "orphan" && "bg-white text-[var(--primary)] shadow-sm")}
              >
                حسب اليتيم
              </button>
            </div>
          }
        >
          <HorizontalValueBars
            data={transferGrouping === "sponsor" ? analytics.transfersBySponsor : analytics.transfersByOrphan}
            compact={compact}
            color={COLORS.teal}
            onSelect={(item) =>
              openDrilldown({
                kind: "transfers",
                title: `تحويلات ${item.label}`,
                ...(transferGrouping === "sponsor" ? { sponsorId: item.id } : { orphanId: item.id })
              })
            }
          />
        </ChartPanel>
      </DashboardSection>

      <DashboardSection
        title="المطابقة الشهرية"
        description="مصفوفة مستقلة تربط حالة دفعة المتبرع بوجود تحويل اليتيم وإيصال التحويل لكل شهر."
      >
        <div className="mb-3 grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
          {(Object.entries(reconciliationMeta) as Array<[ReconciliationStatus, (typeof reconciliationMeta)[ReconciliationStatus]]>).map(
            ([key, meta]) => {
              const Icon = meta.icon;
              return (
                <div key={key} className={cn("flex min-h-11 items-center gap-2 rounded-md border px-3 py-2 text-xs font-bold", meta.className)}>
                  <Icon size={16} className="shrink-0" aria-hidden />
                  <span>{meta.label}</span>
                </div>
              );
            }
          )}
        </div>
        <Card className="overflow-hidden">
          {analytics.reconciliation.length ? (
            <div className="max-h-[720px] divide-y overflow-y-auto">
              {analytics.reconciliation.map((row) => (
                <article key={row.sponsorshipId} className="p-4 sm:p-5">
                  <div className="flex min-w-0 flex-col gap-1 sm:flex-row sm:items-baseline sm:justify-between sm:gap-4">
                    <h3 className="min-w-0 truncate text-sm font-black">{row.sponsorName}</h3>
                    <p className="min-w-0 truncate text-xs text-[var(--ink-faint)]">{row.orphanName} - {row.caseNumber}</p>
                  </div>
                  <div className={cn("mt-4 grid gap-2", row.months.length === 1 ? "grid-cols-1" : "grid-cols-6 sm:grid-cols-12")}>
                    {row.months.map((month) => {
                      const meta = reconciliationMeta[month.status];
                      const Icon = meta.icon;
                      return (
                        <button
                          key={month.month}
                          type="button"
                          title={`${month.label}: ${meta.label}`}
                          aria-label={`${row.sponsorName}، ${row.orphanName}، ${month.label}: ${meta.label}`}
                          onClick={() =>
                            openDrilldown({
                              kind: month.status === "payment_missing_transfer" || month.status === "unpaid" ? "payments" : "transfers",
                              title: `${row.orphanName} - ${month.label}`,
                              month: month.month,
                              orphanId: row.orphanId,
                              sponsorId: row.sponsorId,
                              ...(month.status === "unpaid" ? { paymentStatus: "unpaid" as const } : {}),
                              ...(month.status === "complete" ? { receiptStatus: "with_receipt" as const } : {})
                            })
                          }
                          className={cn("grid min-h-14 place-items-center rounded-md border p-1", meta.className)}
                        >
                          <span className="text-[10px] font-black">{row.months.length === 1 ? month.label : month.month}</span>
                          <Icon size={16} aria-hidden />
                        </button>
                      );
                    })}
                  </div>
                </article>
              ))}
            </div>
          ) : (
            <div className="p-4"><ChartEmpty title="لا توجد علاقات كفالة مطابقة للمصفوفة" /></div>
          )}
        </Card>
      </DashboardSection>

      <DashboardSection
        title="الإيصالات المفقودة"
        description="مقارنة مباشرة بين التحويلات الموثقة والتحويلات التي ما زالت بدون إيصال."
      >
        <div className="grid min-w-0 gap-4 xl:grid-cols-2">
          <ChartPanel title="حالة إيصالات التحويل" note="عدد تحويلات الأيتام في الفترة المحددة.">
            <DonutVisual
              data={analytics.receiptStatus}
              colors={[COLORS.green, COLORS.amber]}
              valueSuffix="تحويل"
              onSelect={(key) =>
                openDrilldown({
                  kind: "transfers",
                  title: key === "with_receipt" ? "التحويلات الموثقة بإيصال" : "التحويلات بدون إيصال",
                  receiptStatus: key as "with_receipt" | "missing_receipt"
                })
              }
            />
          </ChartPanel>
          <Card className="flex min-h-80 min-w-0 flex-col justify-between border-s-4 border-s-amber-500 p-5 sm:p-6">
            <div>
              <span className="grid size-11 place-items-center rounded-md bg-amber-50 text-amber-700">
                <FileWarning size={22} aria-hidden />
              </span>
              <p className="mt-5 text-sm font-bold text-[var(--ink-soft)]">التحويلات بدون إيصال</p>
              <p className="mt-2 text-4xl font-black text-amber-700">{formatReportCount(analytics.kpis.missingReceipts)}</p>
              <p className="mt-3 text-sm leading-7 text-[var(--ink-faint)]">
                من أصل {formatReportCount(analytics.transfers.length)} تحويل مطابق للفلاتر.
              </p>
            </div>
            <button
              type="button"
              onClick={() => openDrilldown({ kind: "transfers", title: "التحويلات بدون إيصال", receiptStatus: "missing_receipt" })}
              className="mt-6 inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-md bg-amber-600 px-4 text-sm font-bold text-white hover:bg-amber-700"
            >
              <ReceiptText size={17} aria-hidden />
              عرض السجلات
            </button>
          </Card>
        </div>
      </DashboardSection>

      <DashboardSection
        title="الكفالات النشطة"
        description="قيمة الالتزامات الشهرية وعدد الأيتام المرتبطين بكل متبرع، مع حالة علاقات الكفالة."
      >
        <div className="grid min-w-0 gap-4 xl:grid-cols-2">
          <ChartPanel title="الالتزام الشهري حسب المتبرع" note="مجموع مبالغ علاقات الكفالة النشطة.">
            <HorizontalValueBars data={analytics.commitmentsBySponsor} compact={compact} amountValues color={COLORS.teal} />
          </ChartPanel>
          <ChartPanel title="عدد الأيتام المرتبطين بكل متبرع" note="العلاقات النشطة فقط.">
            <HorizontalValueBars data={analytics.orphanCountBySponsor} compact={compact} color={COLORS.blue} />
          </ChartPanel>
        </div>
        <ChartPanel className="mt-4" title="الكفالات النشطة والموقوفة" note="العلاقات التي تقع ضمن الفترة المختارة.">
          <DonutVisual
            data={analytics.sponsorshipStatus}
            colors={[COLORS.green, COLORS.gray]}
            valueSuffix="علاقة"
          />
        </ChartPanel>
      </DashboardSection>

      <DashboardSection
        title="تغطية الكفالة"
        description="مقارنة الاحتياج الشهري بالتغطية الحالية لكل يتيم، دون تغيير مبالغ الكفالات المسجلة."
      >
        <div className="mb-4 grid gap-3 sm:grid-cols-3">
          <KpiCard
            label="إجمالي الاحتياج الشهري"
            value={formatReportAmount(analytics.coverageTotals.need)}
            note="للحالات التي لديها احتياج مسجل"
            icon={Banknote}
            tone="blue"
          />
          <KpiCard
            label="إجمالي المبلغ المغطى"
            value={formatReportAmount(analytics.coverageTotals.covered)}
            note="حتى سقف الاحتياج المسجل"
            icon={HeartHandshake}
            tone="green"
          />
          <KpiCard
            label="إجمالي المبلغ المتبقي"
            value={formatReportAmount(analytics.coverageTotals.remaining)}
            note="الفجوة الشهرية الحالية"
            icon={CircleAlert}
            tone="red"
          />
        </div>
        <div className="grid min-w-0 gap-4 xl:grid-cols-2">
          <ChartPanel title="حالة تغطية الأيتام" note="كاملة، جزئية، أو غير مغطاة.">
            <DonutVisual
              data={analytics.coverageStatus}
              colors={[COLORS.green, COLORS.amber, COLORS.red]}
              valueSuffix="حالة"
              onSelect={(key) =>
                openDrilldown({
                  kind: "orphans",
                  title: analytics.coverageStatus.find((item) => item.key === key)?.label ?? "حالات التغطية",
                  coverageCategory: key as "full" | "partial" | "uncovered"
                })
              }
            />
          </ChartPanel>
          <Card className="min-w-0 overflow-hidden">
            <div className="border-b p-4 sm:p-5">
              <h3 className="text-sm font-black sm:text-base">نسبة التغطية لكل يتيم</h3>
              <p className="mt-1 text-xs leading-6 text-[var(--ink-faint)]">مرتبة من الأقل اكتمالاً إلى الأعلى.</p>
            </div>
            {analytics.orphanCoverage.length ? (
              <div className="max-h-[430px] divide-y overflow-y-auto">
                {analytics.orphanCoverage.map((item) => (
                  <Link
                    key={item.id}
                    href={`/admin/orphans/${item.id}`}
                    className="block p-4 hover:bg-slate-50 sm:p-5"
                  >
                    <div className="flex min-w-0 items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="truncate text-sm font-black">{item.name}</p>
                        <p className="mt-1 text-xs text-[var(--ink-faint)]">{item.caseNumber}</p>
                      </div>
                      <Badge tone={item.category === "full" ? "success" : item.category === "partial" ? "warning" : "danger"}>
                        {item.percentage === null ? "الاحتياج غير مسجل" : `${item.percentage}%`}
                      </Badge>
                    </div>
                    <div className="mt-3 h-2 overflow-hidden rounded-full bg-slate-200">
                      <div
                        className={cn("h-full rounded-full", item.category === "full" ? "bg-green-600" : item.category === "partial" ? "bg-amber-500" : "bg-red-500")}
                        style={{ width: `${item.percentage ?? 0}%` }}
                      />
                    </div>
                    <div className="mt-2 flex flex-wrap justify-between gap-2 text-[11px] text-[var(--ink-faint)]">
                      <span>مغطى: {formatReportAmount(item.covered)}</span>
                      <span>{item.remaining === null ? "الاحتياج غير متوفر" : `متبقي: ${formatReportAmount(item.remaining)}`}</span>
                    </div>
                  </Link>
                ))}
              </div>
            ) : (
              <div className="p-4"><ChartEmpty title="لا توجد حالات لعرض التغطية" /></div>
            )}
          </Card>
        </div>
      </DashboardSection>

      <DashboardSection
        title="البيانات والمستندات الناقصة"
        description="مؤشرات جودة ملفات الأيتام استناداً إلى الحقول الأساسية والمستندات الثلاثة المطلوبة."
      >
        <div className="grid min-w-0 gap-4 xl:grid-cols-2">
          <ChartPanel title="عدد الحالات الناقصة لكل عنصر" note="الحقول والمستندات مرتبة حسب أكبر عدد مفقود.">
            <HorizontalValueBars
              data={analytics.missingData.map((item) => ({ ...item, id: item.label }))}
              compact={compact}
              color={COLORS.red}
              onSelect={(item) =>
                openDrilldown({ kind: "orphans", title: `الحالات التي ينقصها: ${item.label}`, missingItem: item.label })
              }
            />
          </ChartPanel>
          <Card className="min-w-0 overflow-hidden">
            <div className="border-b p-4 sm:p-5">
              <h3 className="text-sm font-black sm:text-base">اكتمال ملف كل يتيم</h3>
              <p className="mt-1 text-xs leading-6 text-[var(--ink-faint)]">تحذير واضح للحالات التي لديها عدة نواقص.</p>
            </div>
            {analytics.orphanCompletion.length ? (
              <div className="max-h-[500px] divide-y overflow-y-auto">
                {analytics.orphanCompletion.map((orphan) => (
                  <CompletionRow key={orphan.id} orphan={orphan} />
                ))}
              </div>
            ) : (
              <div className="p-4"><ChartEmpty title="لا توجد ملفات أيتام مطابقة" /></div>
            )}
          </Card>
        </div>
      </DashboardSection>

      <DashboardSection
        title="الملخص السنوي"
        description={`المقارنة الشهرية الشاملة بين دفعات المتبرعين وتحويلات الأيتام لعام ${dataset.year}.`}
      >
        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
          <KpiCard label="المتوقع سنوياً" value={formatReportAmount(analytics.annualTotals.expectedAmount)} note={`عام ${dataset.year}`} icon={CalendarCheck2} tone="blue" />
          <KpiCard label="المدفوع سنوياً" value={formatReportAmount(analytics.annualTotals.receivedAmount)} note={`عام ${dataset.year}`} icon={WalletCards} tone="green" />
          <KpiCard label="غير المدفوع سنوياً" value={formatReportAmount(analytics.annualTotals.unpaidAmount)} note={`عام ${dataset.year}`} icon={CircleAlert} tone="red" />
          <KpiCard label="التحويلات سنوياً" value={formatReportAmount(analytics.annualTotals.transferAmount)} note={`عام ${dataset.year}`} icon={HandCoins} tone="teal" />
        </div>
        <div className="mt-4 grid gap-3 sm:grid-cols-2">
          <ChangeIndicator label="التغير الشهري في دفعات المتبرعين" value={analytics.monthChange.payments} month={analytics.monthChange.month} />
          <ChangeIndicator label="التغير الشهري في تحويلات الأيتام" value={analytics.monthChange.transfers} month={analytics.monthChange.month} />
        </div>
        <div className="mt-4 grid min-w-0 gap-4 xl:grid-cols-2">
          <ChartPanel title="دفعات المتبرعين مقابل تحويلات الأيتام" note="النظامان معروضان كسلسلتين مستقلتين للمقارنة فقط.">
            <AnnualAreaChart data={analytics.annualMonthly} compact={compact} />
          </ChartPanel>
          <ChartPanel title="المتبرعون المدفوعون وغير المدفوعين شهرياً" note="المتبرع غير مدفوع إذا كان لديه التزام غير مدفوع واحد على الأقل في الشهر.">
            <SponsorCountBars data={analytics.annualMonthly} compact={compact} />
          </ChartPanel>
        </div>
      </DashboardSection>

      <DetailedRecords
        analytics={analytics}
        drilldown={drilldown}
        setDrilldown={(next) => {
          setDrilldown(next);
          setDetailLimit(50);
        }}
        detailLimit={detailLimit}
        setDetailLimit={setDetailLimit}
      />
    </div>
  );
}

function FilterSelect({
  label,
  value,
  onChange,
  options
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  options: Array<{ value: string; label: string }>;
}) {
  return (
    <label className="min-w-0">
      <span className="mb-2 block text-xs font-bold text-[var(--ink-soft)]">{label}</span>
      <select
        value={value}
        onChange={(event) => onChange(event.target.value)}
        className="h-11 w-full rounded-md border bg-white px-3 text-sm outline-none focus:border-[var(--primary)] focus:ring-4 focus:ring-[var(--focus)]"
      >
        {options.map((option) => <option key={`${label}-${option.value}`} value={option.value}>{option.label}</option>)}
      </select>
    </label>
  );
}

function CompletionRow({ orphan }: { orphan: ReportOrphan }) {
  const warning = orphan.missingItems.length >= 4;
  const tone = orphan.completionPercentage === 100 ? "success" : warning ? "danger" : "warning";

  return (
    <Link href={`/admin/orphans/${orphan.id}`} className="block p-4 hover:bg-slate-50 sm:p-5">
      <div className="flex min-w-0 items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="truncate text-sm font-black">{orphan.name}</p>
          <p className="mt-1 text-xs text-[var(--ink-faint)]">{orphan.caseNumber}</p>
        </div>
        <Badge tone={tone}>{orphan.completionPercentage}%</Badge>
      </div>
      <div className="mt-3 h-2 overflow-hidden rounded-full bg-slate-200">
        <div
          className={cn("h-full rounded-full", orphan.completionPercentage === 100 ? "bg-green-600" : warning ? "bg-red-500" : "bg-amber-500")}
          style={{ width: `${orphan.completionPercentage}%` }}
        />
      </div>
      {orphan.missingItems.length ? (
        <div className={cn("mt-3 flex items-start gap-2 text-xs leading-6", warning ? "text-red-700" : "text-amber-700")}>
          <FileWarning size={15} className="mt-1 shrink-0" aria-hidden />
          <span>{orphan.missingItems.length} عناصر ناقصة: {orphan.missingItems.slice(0, 3).join("، ")}{orphan.missingItems.length > 3 ? "…" : ""}</span>
        </div>
      ) : (
        <div className="mt-3 flex items-center gap-2 text-xs font-bold text-green-700">
          <CheckCircle2 size={15} aria-hidden />
          الملف مكتمل
        </div>
      )}
    </Link>
  );
}

function DetailedRecords({
  analytics,
  drilldown,
  setDrilldown,
  detailLimit,
  setDetailLimit
}: {
  analytics: ReportAnalytics;
  drilldown: Drilldown;
  setDrilldown: (value: Drilldown) => void;
  detailLimit: number;
  setDetailLimit: React.Dispatch<React.SetStateAction<number>>;
}) {
  const payments = analytics.payments.filter((item) => {
    if (drilldown.kind !== "payments") return false;
    if (drilldown.month && item.month !== drilldown.month) return false;
    if (drilldown.paymentStatus && item.paymentStatus !== drilldown.paymentStatus) return false;
    if (drilldown.orphanId && item.orphanId !== drilldown.orphanId) return false;
    if (drilldown.sponsorId && item.sponsorId !== drilldown.sponsorId) return false;
    return true;
  });
  const transfers = analytics.transfers.filter((item) => {
    if (drilldown.kind !== "transfers") return false;
    if (drilldown.month && item.month !== drilldown.month) return false;
    if (drilldown.receiptStatus === "with_receipt" && !item.hasReceipt) return false;
    if (drilldown.receiptStatus === "missing_receipt" && item.hasReceipt) return false;
    if (drilldown.orphanId && item.orphanId !== drilldown.orphanId) return false;
    if (drilldown.sponsorId && !item.sponsorIds.includes(drilldown.sponsorId)) return false;
    return true;
  });
  const coverageCategoryById = new Map(analytics.orphanCoverage.map((item) => [item.id, item.category]));
  const orphanIdFilter = drilldown.orphanIds ? new Set(drilldown.orphanIds) : null;
  const orphans = analytics.orphans.filter((item) => {
    if (drilldown.kind !== "orphans") return false;
    if (orphanIdFilter && !orphanIdFilter.has(item.id)) return false;
    if (drilldown.missingItem && !item.missingItems.includes(drilldown.missingItem)) return false;
    if (drilldown.coverageCategory && coverageCategoryById.get(item.id) !== drilldown.coverageCategory) return false;
    return true;
  });
  const total = drilldown.kind === "payments" ? payments.length : drilldown.kind === "transfers" ? transfers.length : orphans.length;

  return (
    <section id="report-details" className="scroll-mt-24 pt-10">
      <div className="mb-4 flex min-w-0 flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
        <div className="min-w-0">
          <h2 className="text-lg font-black sm:text-xl">{drilldown.title}</h2>
          <p className="mt-1 text-sm leading-7 text-[var(--ink-soft)]">
            {formatReportCount(total)} سجل للتحقق والمتابعة الإدارية.
          </p>
        </div>
        <div className="grid grid-cols-3 rounded-md border bg-slate-50 p-1">
          <button
            type="button"
            onClick={() => setDrilldown({ kind: "payments", title: "تفاصيل دفعات المتبرعين" })}
            className={cn("min-h-10 rounded px-3 text-xs font-bold", drilldown.kind === "payments" && "bg-white text-[var(--primary)] shadow-sm")}
          >
            الدفعات
          </button>
          <button
            type="button"
            onClick={() => setDrilldown({ kind: "transfers", title: "تفاصيل تحويلات الأيتام" })}
            className={cn("min-h-10 rounded px-3 text-xs font-bold", drilldown.kind === "transfers" && "bg-white text-[var(--primary)] shadow-sm")}
          >
            التحويلات
          </button>
          <button
            type="button"
            onClick={() => setDrilldown({ kind: "orphans", title: "تفاصيل حالات الأيتام" })}
            className={cn("min-h-10 rounded px-3 text-xs font-bold", drilldown.kind === "orphans" && "bg-white text-[var(--primary)] shadow-sm")}
          >
            الحالات
          </button>
        </div>
      </div>

      <Card className="overflow-hidden">
        {total === 0 ? (
          <div className="p-4 sm:p-6"><ChartEmpty title="لا توجد سجلات تفصيلية مطابقة لهذا المؤشر" /></div>
        ) : drilldown.kind === "payments" ? (
          <PaymentRecords records={payments.slice(0, detailLimit)} />
        ) : drilldown.kind === "transfers" ? (
          <TransferRecords records={transfers.slice(0, detailLimit)} />
        ) : (
          <OrphanRecords records={orphans.slice(0, detailLimit)} analytics={analytics} />
        )}
      </Card>

      {total > detailLimit ? (
        <button
          type="button"
          onClick={() => setDetailLimit((current) => current + 50)}
          className="mx-auto mt-4 flex min-h-11 w-full items-center justify-center rounded-md border bg-white px-4 text-sm font-bold hover:bg-slate-50 sm:w-auto"
        >
          عرض المزيد
        </button>
      ) : null}
    </section>
  );
}

function PaymentRecords({ records }: { records: ReportPayment[] }) {
  return (
    <>
      <div className="divide-y lg:hidden">
        {records.map((item) => (
          <article key={item.id} className="p-4">
            <div className="flex min-w-0 items-start justify-between gap-3">
              <div className="min-w-0">
                <h3 className="truncate text-sm font-black">{item.sponsorName}</h3>
                <p className="mt-1 truncate text-xs text-[var(--ink-faint)]">{item.orphanName} - {item.caseNumber}</p>
              </div>
              <Badge tone={item.paymentStatus === "paid" ? "success" : "danger"}>
                {item.paymentStatus === "paid" ? "مدفوع" : "غير مدفوع"}
              </Badge>
            </div>
            <dl className="mt-4 grid grid-cols-2 gap-3 text-xs">
              <div><dt className="text-[var(--ink-faint)]">المتوقع</dt><dd className="mt-1 break-words font-black">{formatReportAmount(item.expectedAmount)}</dd></div>
              <div><dt className="text-[var(--ink-faint)]">المستلم</dt><dd className="mt-1 break-words font-black">{formatReportAmount(item.receivedAmount)}</dd></div>
              <div><dt className="text-[var(--ink-faint)]">الشهر</dt><dd className="mt-1 font-bold">{REPORT_MONTHS[item.month - 1]} {item.year}</dd></div>
              <div><dt className="text-[var(--ink-faint)]">التاريخ</dt><dd className="mt-1 font-bold">{formatDate(item.paymentDate)}</dd></div>
            </dl>
            <div className="mt-4 grid grid-cols-2 gap-2">
              <RecordLink href={`/admin/donors/${item.sponsorId}`} label="المتبرع" />
              <RecordLink href={`/admin/orphans/${item.orphanId}`} label="اليتيم" />
            </div>
          </article>
        ))}
      </div>
      <div className="table-scroll hidden lg:block">
        <table className="w-full min-w-[920px] text-right text-sm">
          <thead className="bg-[var(--surface-muted)] text-xs text-[var(--ink-soft)]">
            <tr>
              <th className="px-4 py-3">المتبرع</th>
              <th className="px-4 py-3">اليتيم</th>
              <th className="px-4 py-3">الفترة</th>
              <th className="px-4 py-3">المتوقع</th>
              <th className="px-4 py-3">المستلم</th>
              <th className="px-4 py-3">الحالة</th>
              <th className="px-4 py-3">التاريخ</th>
              <th className="px-4 py-3"><span className="sr-only">الإجراء</span></th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {records.map((item) => (
              <tr key={item.id}>
                <td className="px-4 py-3 font-bold">{item.sponsorName}</td>
                <td className="px-4 py-3">{item.orphanName} - {item.caseNumber}</td>
                <td className="px-4 py-3">{REPORT_MONTHS[item.month - 1]} {item.year}</td>
                <td className="px-4 py-3">{formatReportAmount(item.expectedAmount)}</td>
                <td className="px-4 py-3 font-black">{formatReportAmount(item.receivedAmount)}</td>
                <td className="px-4 py-3"><Badge tone={item.paymentStatus === "paid" ? "success" : "danger"}>{item.paymentStatus === "paid" ? "مدفوع" : "غير مدفوع"}</Badge></td>
                <td className="px-4 py-3">{formatDate(item.paymentDate)}</td>
                <td className="px-4 py-3"><RecordLink href={`/admin/orphans/${item.orphanId}`} label="فتح" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

function TransferRecords({ records }: { records: ReportTransfer[] }) {
  return (
    <>
      <div className="divide-y lg:hidden">
        {records.map((item) => (
          <article key={item.id} className="p-4">
            <div className="flex min-w-0 items-start justify-between gap-3">
              <div className="min-w-0">
                <h3 className="truncate text-sm font-black">{item.orphanName}</h3>
                <p className="mt-1 truncate text-xs text-[var(--ink-faint)]">{item.caseNumber}</p>
              </div>
              <Badge tone={item.hasReceipt ? "success" : "warning"}>{item.hasReceipt ? "بإيصال" : "بدون إيصال"}</Badge>
            </div>
            <p className="mt-4 break-words text-xl font-black">{formatReportAmount(item.amount)}</p>
            <dl className="mt-3 grid grid-cols-2 gap-3 text-xs">
              <div><dt className="text-[var(--ink-faint)]">الشهر</dt><dd className="mt-1 font-bold">{REPORT_MONTHS[item.month - 1]} {item.year}</dd></div>
              <div><dt className="text-[var(--ink-faint)]">التاريخ</dt><dd className="mt-1 font-bold">{formatDate(item.transferDate)}</dd></div>
            </dl>
            <p className="mt-3 text-xs leading-6 text-[var(--ink-soft)]">{item.sponsorNames.join("، ") || "لا يوجد متبرع مرتبط"}</p>
            <RecordLink className="mt-4 w-full" href={`/admin/orphans/${item.orphanId}`} label="فتح ملف اليتيم" />
          </article>
        ))}
      </div>
      <div className="table-scroll hidden lg:block">
        <table className="w-full min-w-[880px] text-right text-sm">
          <thead className="bg-[var(--surface-muted)] text-xs text-[var(--ink-soft)]">
            <tr>
              <th className="px-4 py-3">اليتيم</th>
              <th className="px-4 py-3">المتبرعون المرتبطون</th>
              <th className="px-4 py-3">الفترة</th>
              <th className="px-4 py-3">المبلغ</th>
              <th className="px-4 py-3">التاريخ</th>
              <th className="px-4 py-3">الإيصال</th>
              <th className="px-4 py-3"><span className="sr-only">الإجراء</span></th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {records.map((item) => (
              <tr key={item.id}>
                <td className="px-4 py-3 font-bold">{item.orphanName} - {item.caseNumber}</td>
                <td className="px-4 py-3">{item.sponsorNames.join("، ") || "غير متوفر"}</td>
                <td className="px-4 py-3">{REPORT_MONTHS[item.month - 1]} {item.year}</td>
                <td className="px-4 py-3 font-black">{formatReportAmount(item.amount)}</td>
                <td className="px-4 py-3">{formatDate(item.transferDate)}</td>
                <td className="px-4 py-3"><Badge tone={item.hasReceipt ? "success" : "warning"}>{item.hasReceipt ? "مرفق" : "مفقود"}</Badge></td>
                <td className="px-4 py-3"><RecordLink href={`/admin/orphans/${item.orphanId}`} label="فتح" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

function OrphanRecords({ records, analytics }: { records: ReportOrphan[]; analytics: ReportAnalytics }) {
  const coverage = new Map(analytics.orphanCoverage.map((item) => [item.id, item]));

  return (
    <div className="grid divide-y md:grid-cols-2 md:divide-x md:divide-y-0 xl:grid-cols-3">
      {records.map((item) => {
        const orphanCoverage = coverage.get(item.id);
        const severalMissing = item.missingItems.length >= 4;
        return (
          <article key={item.id} className="min-w-0 p-4 sm:p-5">
            <div className="flex min-w-0 items-start justify-between gap-3">
              <div className="min-w-0">
                <h3 className="truncate text-sm font-black">{item.name}</h3>
                <p className="mt-1 text-xs text-[var(--ink-faint)]">{item.caseNumber}</p>
              </div>
              <Badge tone={item.completionPercentage === 100 ? "success" : severalMissing ? "danger" : "warning"}>
                {item.completionPercentage}%
              </Badge>
            </div>
            <div className="mt-4 h-2 overflow-hidden rounded-full bg-slate-200">
              <div
                className={cn("h-full rounded-full", item.completionPercentage === 100 ? "bg-green-600" : severalMissing ? "bg-red-500" : "bg-amber-500")}
                style={{ width: `${item.completionPercentage}%` }}
              />
            </div>
            <dl className="mt-4 grid grid-cols-2 gap-3 text-xs">
              <div><dt className="text-[var(--ink-faint)]">الاحتياج</dt><dd className="mt-1 break-words font-bold">{item.monthlyNeed === null ? "غير متوفر" : formatReportAmount(item.monthlyNeed)}</dd></div>
              <div><dt className="text-[var(--ink-faint)]">التغطية</dt><dd className="mt-1 break-words font-bold">{formatReportAmount(orphanCoverage?.covered ?? 0)}</dd></div>
            </dl>
            {item.missingItems.length ? (
              <p className={cn("mt-4 text-xs leading-6", severalMissing ? "text-red-700" : "text-amber-700")}>
                ينقص الملف: {item.missingItems.slice(0, 4).join("، ")}{item.missingItems.length > 4 ? "…" : ""}
              </p>
            ) : (
              <p className="mt-4 text-xs font-bold text-green-700">البيانات والمستندات مكتملة</p>
            )}
            <RecordLink className="mt-4 w-full" href={`/admin/orphans/${item.id}`} label="فتح ملف اليتيم" />
          </article>
        );
      })}
    </div>
  );
}

function RecordLink({ href, label, className }: { href: string; label: string; className?: string }) {
  return (
    <Link
      href={href}
      className={cn("inline-flex min-h-10 items-center justify-center gap-2 rounded-md border px-3 text-xs font-bold text-[var(--primary)] hover:bg-slate-50", className)}
    >
      {label}
      <ExternalLink size={14} aria-hidden />
    </Link>
  );
}
