import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { PageHeader } from "@/components/dashboard/page-header";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { calculateAge, formatSdg } from "@/lib/calculations";
import { MISSING_VALUE, orphanStatusLabels } from "@/lib/constants";
import { requireProfile } from "@/lib/auth";
import { createServerSupabaseClient } from "@/lib/supabase/server";

export default async function SponsorOrphansPage() {
  const profile = await requireProfile("donor");
  const supabase = await createServerSupabaseClient();
  const { data } = await supabase
    .from("sponsorships")
    .select("id,monthly_amount,start_date,status,orphans(id,case_number,full_name,date_of_birth,gender,sponsor_notes,monthly_need,covered_amount,status)")
    .eq("donor_id", profile.id)
    .eq("status", "active")
    .order("created_at", { ascending: false });

  return (
    <>
      <PageHeader title="الحالات المرتبطة" description="لا يعرض هذا القسم إلا الحالات ذات علاقة كفالة نشطة بحسابك." />
      <div className="grid gap-4 lg:grid-cols-2">
        {data?.length ? data.map((relationship) => {
          const orphan = Array.isArray(relationship.orphans) ? relationship.orphans[0] : relationship.orphans;
          if (!orphan) return null;
          const age = calculateAge(orphan.date_of_birth);
          return (
            <Card key={relationship.id} className="min-w-0 p-4 sm:p-5">
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0"><p className="text-xs font-bold text-[var(--ink-faint)]" dir="ltr">{orphan.case_number}</p><h2 className="mt-1 break-words text-base font-black leading-7 sm:text-lg">{orphan.full_name ?? `حالة ${orphan.case_number}`}</h2></div>
                <Badge tone="info">{orphanStatusLabels[orphan.status as keyof typeof orphanStatusLabels]}</Badge>
              </div>
              <div className="mt-3 flex gap-4 text-sm text-[var(--ink-soft)]"><span>{age === null ? MISSING_VALUE : `${age} سنة`}</span><span>{orphan.gender ? (orphan.gender === "male" ? "ذكر" : "أنثى") : MISSING_VALUE}</span></div>
              {orphan.sponsor_notes ? <p className="mt-4 line-clamp-2 text-sm leading-7 text-[var(--ink-soft)]">{orphan.sponsor_notes}</p> : null}
              <div className="mt-5 flex flex-wrap items-end justify-between gap-4 border-t pt-4">
                <div className="min-w-0"><p className="text-xs text-[var(--ink-faint)]">مساهمتك الشهرية</p><p className="mt-1 break-words font-extrabold">{formatSdg(Number(relationship.monthly_amount))}</p></div>
                <Link href={`/donor/orphans/${orphan.id}`} className="inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-md bg-[var(--primary)] px-3 py-2 text-sm font-bold text-white sm:w-auto">التفاصيل <ArrowLeft size={16} /></Link>
              </div>
            </Card>
          );
        }) : <div className="lg:col-span-2"><Card><EmptyState title="لا توجد حالات مرتبطة" description="تواصل مع الإدارة عند الحاجة إلى مراجعة حسابك." /></Card></div>}
      </div>
    </>
  );
}
