import Link from "next/link";
import { Bell, BookUser, HandCoins, ReceiptText, 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 { formatSdg } from "@/lib/calculations";
import { requireProfile } from "@/lib/auth";
import { createServerSupabaseClient } from "@/lib/supabase/server";

export default async function SponsorDashboardPage() {
  const profile = await requireProfile("donor");
  const supabase = await createServerSupabaseClient();
  const now = new Date();
  const [relationships, monthly, notifications, contributionTotalResult] = await Promise.all([
    supabase
      .from("sponsorships")
      .select("id,monthly_amount,start_date,orphans(id,case_number,full_name,status)")
      .eq("donor_id", profile.id)
      .eq("status", "active"),
    supabase
      .from("orphan_transfers")
      .select("id,amount")
      .eq("transfer_year", now.getFullYear())
      .eq("transfer_month", now.getMonth() + 1),
    supabase
      .from("notifications")
      .select("id,title,body,link,read_at,created_at")
      .eq("recipient_id", profile.id)
      .order("created_at", { ascending: false })
      .limit(5),
    supabase.rpc("get_my_total_contributions")
  ]);
  if (contributionTotalResult.error) {
    throw new Error("تعذر تحميل إجمالي تبرعاتك");
  }
  const monthlyContribution = (relationships.data ?? []).reduce((sum, item) => sum + Number(item.monthly_amount), 0);
  const transferred = (monthly.data ?? []).reduce((sum, item) => sum + Number(item.amount), 0);
  const totalContributions = Number(contributionTotalResult.data ?? 0);
  const unread = (notifications.data ?? []).filter((item) => !item.read_at).length;

  return (
    <>
      <PageHeader title={`مرحباً، ${profile.full_name}`} description="ملخص الحالات التي ربطتها الإدارة بحسابك وسجل تحويلاتها." />
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
        <StatCard icon={BookUser} label="الحالات المرتبطة" value={relationships.data?.length ?? 0} />
        <StatCard icon={HandCoins} label="إجمالي التزامك الشهري" value={formatSdg(monthlyContribution)} />
        <StatCard icon={WalletCards} label="إجمالي تبرعاتك" value={formatSdg(totalContributions)} note="إجمالي التحويلات المرتبطة بحسابك" />
        <StatCard icon={ReceiptText} label="المحول للحالات هذا الشهر" value={formatSdg(transferred)} />
        <StatCard icon={Bell} label="إشعارات غير مقروءة" value={unread} />
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-[1.2fr_.8fr]">
        <Card className="overflow-hidden">
          <div className="flex flex-wrap items-center justify-between gap-2 border-b px-4 py-4 sm:px-5">
            <h2 className="font-black">الحالات المرتبطة</h2>
            <Link href="/donor/orphans" className="text-sm font-bold text-[var(--primary)]">عرض الكل</Link>
          </div>
          {relationships.data?.length ? (
            <div className="divide-y">
              {relationships.data.map((relationship) => {
                const orphan = Array.isArray(relationship.orphans) ? relationship.orphans[0] : relationship.orphans;
                return (
                  <Link key={relationship.id} href={`/donor/orphans/${orphan?.id}`} className="flex min-w-0 flex-wrap items-center justify-between gap-3 px-4 py-4 hover:bg-[var(--surface-muted)] sm:px-5">
                    <div className="min-w-0">
                      <p className="break-words text-sm font-bold leading-7"><span dir="ltr">{orphan?.case_number}</span> - {orphan?.full_name ?? `حالة ${orphan?.case_number}`}</p>
                      <p className="mt-1 break-words text-xs leading-6 text-[var(--ink-faint)]">مساهمتك {formatSdg(Number(relationship.monthly_amount))}</p>
                    </div>
                    <span className="text-sm font-bold text-[var(--primary)]">التفاصيل</span>
                  </Link>
                );
              })}
            </div>
          ) : <EmptyState title="لا توجد حالات مرتبطة" description="تظهر الحالات بعد أن تنشئ الإدارة علاقة الكفالة." />}
        </Card>
        <Card className="overflow-hidden">
          <div className="flex flex-wrap items-center justify-between gap-2 border-b px-4 py-4 sm:px-5">
            <h2 className="font-black">أحدث الإشعارات</h2>
            <Link href="/donor/notifications" className="text-sm font-bold text-[var(--primary)]">عرض الكل</Link>
          </div>
          {notifications.data?.length ? (
            <div className="divide-y">
              {notifications.data.map((notification) => (
                <div key={notification.id} className="px-4 py-4 sm:px-5">
                  <p className="text-sm font-bold">{notification.title}</p>
                  <p className="mt-1 line-clamp-2 text-sm leading-6 text-[var(--ink-soft)]">{notification.body}</p>
                </div>
              ))}
            </div>
          ) : <EmptyState title="لا توجد إشعارات" description="ستظهر رسائل الإدارة هنا." />}
        </Card>
      </div>
    </>
  );
}
