import Link from "next/link";
import { ArrowLeft, Search, UserPlus } from "lucide-react";
import { createSponsorAction } 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 { formatSdg } from "@/lib/calculations";
import { formatDate } from "@/lib/dates";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";

export default async function SponsorsPage({
  searchParams
}: {
  searchParams: Promise<{ q?: string; success?: string; error?: string }>;
}) {
  const params = await searchParams;
  const supabase = createAdminSupabaseClient();
  const query = params.q?.trim().replace(/[,%()]/g, "");
  let request = supabase
    .from("profiles")
    .select("id,full_name,phone,is_active,created_at,sponsorships!sponsorships_donor_id_fkey(id,orphan_id,monthly_amount,status)")
    .eq("role", "donor")
    .is("deleted_at", null)
    .order("created_at", { ascending: false })
    .limit(200);
  if (query) request = request.or(`full_name.ilike.%${query}%,phone.ilike.%${query}%`);
  const { data } = await request;
  const sponsorRows = (data ?? []).map((sponsor) => {
    const active = (sponsor.sponsorships ?? []).filter((item) => item.status === "active");
    return {
      id: sponsor.id,
      fullName: sponsor.full_name,
      phone: sponsor.phone,
      isActive: sponsor.is_active,
      linkedOrphans: new Set(active.map((item) => item.orphan_id)).size,
      monthly: active.reduce((sum, item) => sum + Number(item.monthly_amount), 0),
      createdAt: sponsor.created_at
    };
  });

  return (
    <>
      <PageHeader title="المتبرعون والحسابات" description="إنشاء حسابات الهاتف وإدارة الحالة والكفالات والمساهمات الشهرية." />
      <Notice success={params.success} error={params.error} />

      <form className="mb-5 grid gap-3 sm:grid-cols-[minmax(0,1fr)_auto]">
        <Input name="q" defaultValue={params.q} placeholder="اسم المتبرع أو رقم الهاتف" />
        <button className="inline-flex h-11 w-full items-center justify-center gap-2 rounded-md border bg-white px-4 text-sm font-bold sm:w-auto">
          <Search size={17} aria-hidden />
          بحث
        </button>
      </form>

      {sponsorRows.length ? (
        <>
          <div className="grid gap-3 xl:hidden">
            {sponsorRows.map((sponsor) => (
              <Card key={sponsor.id} className="min-w-0 p-4">
                <div className="flex min-w-0 items-start justify-between gap-3">
                  <div className="min-w-0">
                    <h2 className="break-words font-black leading-7">{sponsor.fullName}</h2>
                    <p className="mt-1 text-sm text-[var(--ink-soft)]" dir="ltr">{sponsor.phone}</p>
                  </div>
                  <Badge tone={sponsor.isActive ? "success" : "danger"}>{sponsor.isActive ? "نشط" : "موقوف"}</Badge>
                </div>
                <dl className="mt-4 divide-y border-y text-sm">
                  <div className="flex flex-wrap justify-between gap-2 py-3">
                    <dt className="text-[var(--ink-soft)]">الحالات المرتبطة</dt>
                    <dd className="font-extrabold">{sponsor.linkedOrphans}</dd>
                  </div>
                  <div className="flex flex-wrap justify-between gap-2 py-3">
                    <dt className="text-[var(--ink-soft)]">المساهمة الشهرية</dt>
                    <dd className="break-words font-extrabold">{formatSdg(sponsor.monthly)}</dd>
                  </div>
                  <div className="flex flex-wrap justify-between gap-2 py-3">
                    <dt className="text-[var(--ink-soft)]">تاريخ الإنشاء</dt>
                    <dd>{formatDate(sponsor.createdAt)}</dd>
                  </div>
                </dl>
                <Link
                  href={`/admin/donors/${sponsor.id}`}
                  className="mt-4 inline-flex min-h-11 w-full items-center justify-center gap-1 rounded-md border font-bold text-[var(--primary)]"
                >
                  إدارة <ArrowLeft size={15} aria-hidden />
                </Link>
              </Card>
            ))}
          </div>
          <Card className="hidden overflow-hidden xl: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>
                  <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">
                {sponsorRows.map((sponsor) => (
                    <tr key={sponsor.id}>
                      <td className="px-4 py-3 font-bold">{sponsor.fullName}</td>
                      <td className="px-4 py-3" dir="ltr">{sponsor.phone}</td>
                      <td className="px-4 py-3"><Badge tone={sponsor.isActive ? "success" : "danger"}>{sponsor.isActive ? "نشط" : "موقوف"}</Badge></td>
                      <td className="px-4 py-3">{sponsor.linkedOrphans}</td>
                      <td className="px-4 py-3 font-extrabold">{formatSdg(sponsor.monthly)}</td>
                      <td className="px-4 py-3">{formatDate(sponsor.createdAt)}</td>
                      <td className="px-4 py-3">
                        <Link href={`/admin/donors/${sponsor.id}`} className="inline-flex items-center gap-1 font-bold text-[var(--primary)]">
                          إدارة <ArrowLeft size={15} aria-hidden />
                        </Link>
                      </td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </Card>
        </>
      ) : <Card><EmptyState title="لا يوجد متبرعون" description="أنشئ أول حساب متبرع من النموذج أدناه." /></Card>}

      <section className="mt-8">
        <div className="mb-4 flex items-center gap-2">
          <UserPlus size={19} className="text-[var(--primary)]" aria-hidden />
          <h2 className="text-lg font-black">إنشاء حساب متبرع</h2>
        </div>
        <Card className="p-5">
          <form action={createSponsorAction} className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
            <div><Label>الاسم الكامل</Label><Input name="fullName" required /></div>
            <div><Label>رقم الهاتف</Label><Input name="phone" type="tel" dir="ltr" placeholder="+249912345678" required /></div>
            <div><Label>كلمة المرور الأولية</Label><Input name="password" type="password" dir="ltr" minLength={6} autoComplete="new-password" required /></div>
            <label className="flex h-11 items-center gap-2 self-end rounded-md border bg-white px-3 text-sm font-semibold">
              <input name="isActive" type="checkbox" defaultChecked />
              حساب نشط
            </label>
            <SubmitButton pendingText="جارٍ إنشاء الحساب..." className="w-full sm:w-auto sm:justify-self-start">
              <UserPlus size={17} aria-hidden />
              إنشاء الحساب
            </SubmitButton>
          </form>
        </Card>
      </section>
    </>
  );
}
