import Link from "next/link";
import { createSponsorshipAction, updateSponsorshipAction } from "@/app/actions/admin";
import { Notice } from "@/components/dashboard/notice";
import { PageHeader } from "@/components/dashboard/page-header";
import { SubmitButton } from "@/components/forms/submit-button";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { DEFAULT_MONTHLY_SUPPORT, sponsorshipStatusLabels } from "@/lib/constants";
import { formatDate, todayIso } from "@/lib/dates";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";

export default async function SponsorshipsPage({ searchParams }: { searchParams: Promise<{ success?: string; error?: string }> }) {
  const messages = await searchParams;
  const supabase = createAdminSupabaseClient();
  const [sponsorships, sponsors, orphans] = await Promise.all([
    supabase
      .from("sponsorships")
      .select("id,donor_id,orphan_id,monthly_amount,status,start_date,end_date,stop_reason,notes,profiles!sponsorships_donor_id_fkey(full_name),orphans(case_number,full_name)")
      .order("created_at", { ascending: false })
      .limit(200),
    supabase.from("profiles").select("id,full_name,phone").eq("role", "donor").eq("is_active", true).order("full_name"),
    supabase.from("orphans").select("id,case_number,full_name").not("status", "in", "(paused,archived)").order("case_number")
  ]);

  return (
    <>
      <PageHeader title="علاقات الكفالة" description="إنشاء العلاقات وتعديل المساهمات وإنهاؤها مع الاحتفاظ بالتاريخ." />
      <Notice success={messages.success} error={messages.error} />
      {sponsorships.data?.length ? (
        <div className="grid gap-4 xl:grid-cols-2">
          {sponsorships.data.map((item) => {
            const sponsor = Array.isArray(item.profiles) ? item.profiles[0] : item.profiles;
            const orphan = Array.isArray(item.orphans) ? item.orphans[0] : item.orphans;
            return (
              <Card key={item.id} className="min-w-0 overflow-hidden">
                <div className="p-4 sm:p-5">
                  <div className="flex min-w-0 items-start justify-between gap-3">
                    <div className="min-w-0">
                      <Link
                        href={`/admin/donors/${item.donor_id}`}
                        className="block break-words font-black leading-7 text-[var(--primary)]"
                      >
                        {sponsor?.full_name}
                      </Link>
                      <Link
                        href={`/admin/orphans/${item.orphan_id}`}
                        className="mt-1 block break-words text-sm font-bold leading-7"
                      >
                        <span dir="ltr">{orphan?.case_number}</span> - {orphan?.full_name ?? `حالة ${orphan?.case_number}`}
                      </Link>
                    </div>
                    <Badge tone={item.status === "active" ? "success" : item.status === "ended" ? "danger" : "warning"}>
                      {sponsorshipStatusLabels[item.status as keyof typeof sponsorshipStatusLabels]}
                    </Badge>
                  </div>
                  <p className="mt-3 text-sm text-[var(--ink-soft)]">
                    تاريخ البداية: <span className="font-bold text-[var(--ink)]">{formatDate(item.start_date)}</span>
                  </p>
                </div>
                <details className="border-t p-4 sm:p-5">
                  <summary className="cursor-pointer text-sm font-black text-[var(--primary)]">تعديل العلاقة</summary>
                  <form action={updateSponsorshipAction} className="mt-4 grid gap-4 sm:grid-cols-2">
                    <input type="hidden" name="id" value={item.id} />
                    <input type="hidden" name="returnTo" value="/admin/sponsorships" />
                    <div><Label>المساهمة</Label><Input name="monthlyAmount" type="number" min={1000} defaultValue={item.monthly_amount} required /></div>
                    <div>
                      <Label>الحالة</Label>
                      <select name="status" defaultValue={item.status} className="h-11 w-full rounded-md border bg-white px-3 text-sm">
                        <option value="active">نشطة</option>
                        <option value="paused">موقوفة</option>
                        <option value="ended">منتهية</option>
                      </select>
                    </div>
                    <div><Label>تاريخ النهاية</Label><Input name="endDate" type="date" defaultValue={item.end_date ?? ""} /></div>
                    <div><Label>سبب الإيقاف</Label><Input name="stopReason" defaultValue={item.stop_reason ?? ""} /></div>
                    <input type="hidden" name="notes" value={item.notes ?? ""} />
                    <SubmitButton pendingText="جارٍ الحفظ..." variant="secondary" size="sm" className="w-full sm:w-auto sm:justify-self-start">
                      حفظ التعديل
                    </SubmitButton>
                  </form>
                </details>
              </Card>
            );
          })}
        </div>
      ) : <Card><EmptyState title="لا توجد علاقات كفالة" description="أنشئ أول علاقة من النموذج أدناه." /></Card>}

      <section className="mt-8">
        <h2 className="mb-4 text-lg font-black">إنشاء علاقة كفالة</h2>
        <Card className="p-5">
          <form action={createSponsorshipAction} className="grid gap-5 sm:grid-cols-2 lg:grid-cols-5">
            <input type="hidden" name="returnTo" value="/admin/sponsorships" />
            <div><Label>المتبرع</Label><select name="donorId" required className="h-11 w-full rounded-md border bg-white px-3 text-sm"><option value="">اختر المتبرع</option>{sponsors.data?.map((sponsor) => <option key={sponsor.id} value={sponsor.id}>{sponsor.full_name} - {sponsor.phone}</option>)}</select></div>
            <div><Label>الحالة</Label><select name="orphanId" required className="h-11 w-full rounded-md border bg-white px-3 text-sm"><option value="">اختر الحالة</option>{orphans.data?.map((orphan) => <option key={orphan.id} value={orphan.id}>{orphan.full_name ?? `حالة ${orphan.case_number}`} - {orphan.case_number}</option>)}</select></div>
            <div><Label>المساهمة الشهرية</Label><Input name="monthlyAmount" type="number" min={1000} defaultValue={DEFAULT_MONTHLY_SUPPORT} required /></div>
            <div><Label>تاريخ البداية</Label><Input name="startDate" type="date" defaultValue={todayIso()} required /></div>
            <div><Label>ملاحظات</Label><Input name="notes" /></div>
            <SubmitButton pendingText="جارٍ إنشاء العلاقة..." className="w-full sm:w-auto sm:justify-self-start">إنشاء العلاقة</SubmitButton>
          </form>
        </Card>
      </section>
    </>
  );
}
