import Link from "next/link";
import { BookUser, CircleDollarSign, Handshake, UsersRound, WalletCards } from "lucide-react";
import { PageHeader } from "@/components/dashboard/page-header";
import { StatCard } from "@/components/dashboard/stat-card";
import { Card } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Badge } from "@/components/ui/badge";
import { formatSdg } from "@/lib/calculations";
import { sponsorshipStatusLabels } from "@/lib/constants";
import { currentPeriod } from "@/lib/dates";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";

export default async function AdminDashboardPage() {
  const supabase = createAdminSupabaseClient();
  const period = currentPeriod();
  const [orphans, sponsors, relationships, monthly, transfers, latestRelationships] = await Promise.all([
    supabase.from("orphans").select("id", { count: "exact", head: true }).not("status", "eq", "archived"),
    supabase.from("profiles").select("id", { count: "exact", head: true }).eq("role", "donor").eq("is_active", true),
    supabase.from("sponsorships").select("id", { count: "exact", head: true }).eq("status", "active"),
    supabase
      .from("sponsor_monthly_payments")
      .select("expected_amount_snapshot,received_amount")
      .eq("payment_year", period.year)
      .eq("payment_month", period.month),
    supabase
      .from("orphan_transfers")
      .select("amount")
      .eq("transfer_year", period.year)
      .eq("transfer_month", period.month),
    supabase
      .from("sponsorships")
      .select("id,donor_id,orphan_id,monthly_amount,status,start_date,profiles!sponsorships_donor_id_fkey(full_name),orphans(case_number,full_name)")
      .order("created_at", { ascending: false })
      .limit(8)
  ]);
  const totals = (monthly.data ?? []).reduce(
    (sum, row) => ({
      expected: sum.expected + Number(row.expected_amount_snapshot),
      received: sum.received + Number(row.received_amount)
    }),
    { expected: 0, received: 0 }
  );
  const transferred = (transfers.data ?? []).reduce((sum, row) => sum + Number(row.amount), 0);
  const relationshipRows = (latestRelationships.data ?? []).map((relationship) => {
    const sponsor = Array.isArray(relationship.profiles) ? relationship.profiles[0] : relationship.profiles;
    const orphan = Array.isArray(relationship.orphans) ? relationship.orphans[0] : relationship.orphans;
    return {
      id: relationship.id,
      donorId: relationship.donor_id,
      orphanId: relationship.orphan_id,
      sponsorName: sponsor?.full_name,
      orphanName: orphan?.full_name ?? `حالة ${orphan?.case_number}`,
      caseNumber: orphan?.case_number,
      monthlyAmount: Number(relationship.monthly_amount),
      status: relationship.status
    };
  });

  return (
    <>
      <PageHeader title="نظرة عامة" description="ملخص الحالات والمتبرعين والعلاقات والحركة المالية للشهر الحالي." />
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
        <StatCard icon={BookUser} label="الحالات غير المؤرشفة" value={orphans.count ?? 0} />
        <StatCard icon={UsersRound} label="المتبرعون النشطون" value={sponsors.count ?? 0} />
        <StatCard icon={Handshake} label="العلاقات النشطة" value={relationships.count ?? 0} />
        <StatCard icon={WalletCards} label="المتوقع من المتبرعين" value={formatSdg(totals.expected)} />
        <StatCard icon={CircleDollarSign} label="المستلم هذا الشهر" value={formatSdg(totals.received)} note={`المطلوب ${formatSdg(totals.expected)}`} />
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-[1.4fr_.6fr]">
        <section className="min-w-0">
          <h2 className="mb-3 font-extrabold">أحدث علاقات الكفالة</h2>
          {relationshipRows.length ? (
            <>
              <div className="grid gap-3 md:hidden">
                {relationshipRows.map((relationship) => (
                  <Card key={relationship.id} className="min-w-0 p-4">
                    <div className="flex min-w-0 items-start justify-between gap-3">
                      <div className="min-w-0">
                        <Link
                          href={`/admin/donors/${relationship.donorId}`}
                          className="block break-words font-bold text-[var(--primary)]"
                        >
                          {relationship.sponsorName}
                        </Link>
                        <Link
                          href={`/admin/orphans/${relationship.orphanId}`}
                          className="mt-1 block break-words text-sm leading-7"
                        >
                          <span dir="ltr">{relationship.caseNumber}</span> - {relationship.orphanName}
                        </Link>
                      </div>
                      <Badge tone={relationship.status === "active" ? "success" : relationship.status === "ended" ? "danger" : "warning"}>
                        {sponsorshipStatusLabels[relationship.status as keyof typeof sponsorshipStatusLabels]}
                      </Badge>
                    </div>
                    <p className="mt-3 border-t pt-3 text-sm text-[var(--ink-soft)]">
                      المساهمة: <strong className="text-[var(--ink)]">{formatSdg(relationship.monthlyAmount)}</strong>
                    </p>
                  </Card>
                ))}
              </div>
              <Card className="hidden overflow-hidden md:block">
                <table className="w-full 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></tr>
                  </thead>
                  <tbody className="divide-y">
                    {relationshipRows.map((relationship) => (
                      <tr key={relationship.id}>
                        <td className="px-4 py-3"><Link href={`/admin/donors/${relationship.donorId}`} className="font-bold text-[var(--primary)]">{relationship.sponsorName}</Link></td>
                        <td className="px-4 py-3"><Link href={`/admin/orphans/${relationship.orphanId}`}><span dir="ltr">{relationship.caseNumber}</span> - {relationship.orphanName}</Link></td>
                        <td className="px-4 py-3">{formatSdg(relationship.monthlyAmount)}</td>
                        <td className="px-4 py-3"><Badge tone={relationship.status === "active" ? "success" : relationship.status === "ended" ? "danger" : "warning"}>{sponsorshipStatusLabels[relationship.status as keyof typeof sponsorshipStatusLabels]}</Badge></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </Card>
            </>
          ) : <Card><EmptyState title="لا توجد علاقات" description="أنشئ حساب متبرع ثم اربطه بحالة." /></Card>}
        </section>

        <Card className="p-5">
          <h2 className="font-extrabold">حركة الشهر</h2>
          <dl className="mt-5 divide-y text-sm">
            <Row label="المتوقع من المتبرعين" value={formatSdg(totals.expected)} />
            <Row label="دفعات المتبرعين المستلمة" value={formatSdg(totals.received)} />
            <Row label="التحويلات إلى الأيتام" value={formatSdg(transferred)} />
          </dl>
        </Card>
      </div>
    </>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return <div className="flex flex-wrap justify-between gap-x-3 gap-y-1 py-3"><dt className="text-[var(--ink-soft)]">{label}</dt><dd className="break-words font-extrabold">{value}</dd></div>;
}
