import Link from "next/link";
import { notFound } from "next/navigation";
import { KeyRound, Link2, Power, UserRound } from "lucide-react";
import {
  createSponsorshipAction,
  deleteSponsorAccountAction,
  resetAccountPasswordAction,
  setSponsorStatusAction,
  updateSponsorAction,
  updateSponsorshipAction
} from "@/app/actions/admin";
import { Notice } from "@/components/dashboard/notice";
import { PageHeader } from "@/components/dashboard/page-header";
import { ConfirmActionForm } from "@/components/forms/confirm-action-form";
import { SubmitButton } from "@/components/forms/submit-button";
import { SecureImageViewer } from "@/components/media/secure-image-viewer";
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 {
  DEFAULT_MONTHLY_SUPPORT,
  MISSING_DOCUMENT,
  paymentStatusLabels,
  sponsorshipStatusLabels,
  transferStatusLabels
} from "@/lib/constants";
import { formatDate, formatMonthYear, todayIso } from "@/lib/dates";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";

type Related<T> = T | T[] | null;
function one<T>(value: Related<T>): T | null {
  return Array.isArray(value) ? value[0] ?? null : value;
}

export default async function SponsorDetailsPage({
  params,
  searchParams
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ success?: string; error?: string }>;
}) {
  const { id } = await params;
  const messages = await searchParams;
  const supabase = createAdminSupabaseClient();
  const [sponsorResult, relationshipsResult, orphansResult, paymentsResult, transfersResult] = await Promise.all([
    supabase.from("profiles").select("id,full_name,phone,is_active,created_at,updated_at").eq("id", id).eq("role", "donor").is("deleted_at", null).maybeSingle(),
    supabase
      .from("sponsorships")
      .select("id,orphan_id,monthly_amount,status,start_date,end_date,stop_reason,notes,created_at,updated_at,orphans(id,case_number,full_name)")
      .eq("donor_id", id)
      .order("created_at", { ascending: false }),
    supabase.from("orphans").select("id,case_number,full_name,status").order("case_number"),
    supabase
      .from("sponsor_monthly_payments")
      .select("id,orphan_id,payment_year,payment_month,expected_amount_snapshot,received_amount,payment_status,payment_date,orphans(case_number,full_name)")
      .eq("sponsor_id", id)
      .order("payment_year", { ascending: false })
      .order("payment_month", { ascending: false })
      .limit(120),
    supabase
      .from("orphan_transfers")
      .select("id,orphan_id,transfer_year,transfer_month,amount,transfer_date,status,sponsor_visible_notes,orphan_transfer_sponsors!inner(sponsor_id),orphans(case_number,full_name),transfer_receipts(file_assets(id,mime_type))")
      .eq("orphan_transfer_sponsors.sponsor_id", id)
      .order("transfer_year", { ascending: false })
      .order("transfer_month", { ascending: false })
      .limit(120)
  ]);
  if (!sponsorResult.data) notFound();
  const sponsor = sponsorResult.data;
  const destination = `/admin/donors/${id}`;
  const activeRelationships = (relationshipsResult.data ?? []).filter((item) => item.status === "active");
  const historicalTransferred = (transfersResult.data ?? []).reduce((sum, transfer) => sum + Number(transfer.amount), 0);
  const historicalContributions = (paymentsResult.data ?? []).reduce((sum, payment) => sum + Number(payment.received_amount), 0);

  return (
    <>
      <PageHeader
        title={sponsor.full_name}
        description={`حساب متبرع منذ ${formatDate(sponsor.created_at)}`}
        action={<Badge tone={sponsor.is_active ? "success" : "danger"}>{sponsor.is_active ? "حساب نشط" : "حساب موقوف"}</Badge>}
      />
      <Notice success={messages.success} error={messages.error} />

      <div className="grid gap-6 xl:grid-cols-2">
        <Card className="p-5">
          <div className="mb-4 flex items-center gap-2"><UserRound size={19} className="text-[var(--primary)]" aria-hidden /><h2 className="font-black">بيانات الحساب</h2></div>
          <form action={updateSponsorAction} className="grid gap-4 sm:grid-cols-2">
            <input type="hidden" name="id" value={id} />
            <div><Label>الاسم الكامل</Label><Input name="fullName" defaultValue={sponsor.full_name} required /></div>
            <div><Label>رقم الهاتف</Label><Input name="phone" type="tel" dir="ltr" defaultValue={sponsor.phone ?? ""} required /></div>
            <SubmitButton pendingText="جارٍ الحفظ..." size="sm" className="w-full sm:w-auto sm:justify-self-start">حفظ التعديلات</SubmitButton>
          </form>
          <form action={setSponsorStatusAction} className="mt-5 border-t pt-5">
            <input type="hidden" name="id" value={id} />
            <input type="hidden" name="active" value={sponsor.is_active ? "false" : "true"} />
            <SubmitButton
              pendingText={sponsor.is_active ? "جارٍ إيقاف الحساب..." : "جارٍ تفعيل الحساب..."}
              variant={sponsor.is_active ? "danger" : "secondary"}
              size="sm"
            >
              <Power size={17} aria-hidden />
              {sponsor.is_active ? "إيقاف الحساب" : "تفعيل الحساب"}
            </SubmitButton>
          </form>
        </Card>

        <Card className="p-5">
          <div className="mb-4 flex items-center gap-2"><KeyRound size={19} className="text-[var(--primary)]" aria-hidden /><h2 className="font-black">إعادة تعيين كلمة المرور</h2></div>
          <form action={resetAccountPasswordAction} className="grid gap-4 sm:grid-cols-2">
            <input type="hidden" name="id" value={id} />
            <input type="hidden" name="returnTo" value={destination} />
            <div><Label>كلمة المرور الجديدة</Label><Input name="password" type="password" dir="ltr" minLength={6} autoComplete="new-password" required /></div>
            <div><Label>تأكيد كلمة المرور</Label><Input name="confirmation" type="password" dir="ltr" minLength={6} autoComplete="new-password" required /></div>
            <SubmitButton pendingText="جارٍ تعيين كلمة المرور..." variant="secondary" size="sm" className="w-full sm:w-auto sm:justify-self-start">تعيين كلمة المرور</SubmitButton>
          </form>
          <p className="mt-4 text-xs leading-6 text-[var(--ink-faint)]">لا تحتاج إلى كلمة المرور القديمة. تستخدم كلمة المرور الجديدة أثناء العملية فقط ولا تحفظ أو تعرض بعد الإرسال.</p>
        </Card>
      </div>

      <Card className="mt-6 border border-[#e1b6b7] bg-[#fffafa] p-5">
        <h2 className="font-black text-[#7d292b]">حذف حساب المتبرع</h2>
        <p className="mt-2 max-w-3xl text-sm font-semibold leading-7 text-[#7d292b]">
          سيُوقف تسجيل الدخول ويُخفى الحساب من إدارة المتبرعين. لن تحذف التحويلات أو الإيصالات أو الدفعات أو المستندات أو علاقات الكفالة المرتبطة به.
        </p>
        <ConfirmActionForm
          action={deleteSponsorAccountAction}
          fields={{ id }}
          label="حذف حساب المتبرع"
          pendingText="جارٍ حذف الحساب..."
          confirmMessage={`هل تريد حذف حساب ${sponsor.full_name}؟ ستبقى جميع السجلات المالية والمستندات محفوظة.`}
          className="mt-4"
        />
      </Card>

      <div className="mt-6 grid gap-4 sm:grid-cols-3">
        <Summary label="الحالات المرتبطة حالياً" value={String(new Set(activeRelationships.map((item) => item.orphan_id)).size)} />
        <Summary label="دفعات المتبرع المسجلة" value={formatSdg(historicalContributions)} />
        <Summary label="التحويلات المرتبطة بالمتبرع" value={formatSdg(historicalTransferred)} />
      </div>

      <section className="mt-8">
        <div className="mb-4 flex items-center gap-2"><Link2 size={19} className="text-[var(--primary)]" /><h2 className="text-lg font-black">ربط حالة جديدة</h2></div>
        <Card className="p-5">
          <form action={createSponsorshipAction} className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
            <input type="hidden" name="donorId" value={id} />
            <input type="hidden" name="returnTo" value={destination} />
            <div className="lg:col-span-2">
              <Label>الحالة</Label>
              <select name="orphanId" required className="h-11 w-full rounded-md border bg-white px-3 text-sm">
                <option value="">اختر الحالة</option>
                {(orphansResult.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="جارٍ إنشاء العلاقة..." size="sm" className="w-full sm:w-auto sm:justify-self-start">إنشاء العلاقة</SubmitButton>
          </form>
        </Card>
      </section>

      <section className="mt-8">
        <h2 className="mb-4 text-lg font-black">علاقات الكفالة</h2>
        <div className="grid gap-4">
          {relationshipsResult.data?.length ? relationshipsResult.data.map((relationship) => {
            const orphan = one(relationship.orphans);
            return (
              <Card key={relationship.id} className="p-5">
                <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
                  <div>
                    <Link href={`/admin/orphans/${relationship.orphan_id}`} className="font-black text-[var(--primary)]">{orphan?.full_name ?? `حالة ${orphan?.case_number}`} - {orphan?.case_number}</Link>
                    <p className="mt-1 text-xs text-[var(--ink-faint)]">بدأت في {formatDate(relationship.start_date)}</p>
                  </div>
                  <Badge tone={relationship.status === "active" ? "success" : relationship.status === "ended" ? "danger" : "warning"}>
                    {sponsorshipStatusLabels[relationship.status as keyof typeof sponsorshipStatusLabels]}
                  </Badge>
                </div>
                <form action={updateSponsorshipAction} className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                  <input type="hidden" name="id" value={relationship.id} />
                  <input type="hidden" name="returnTo" value={destination} />
                  <div><Label>المساهمة الشهرية</Label><Input name="monthlyAmount" type="number" min={1000} defaultValue={relationship.monthly_amount} required /></div>
                  <div>
                    <Label>الحالة</Label>
                    <select name="status" defaultValue={relationship.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={relationship.end_date ?? ""} /></div>
                  <div><Label>سبب الإيقاف</Label><Input name="stopReason" defaultValue={relationship.stop_reason ?? ""} /></div>
                  <div><Label>ملاحظات</Label><Input name="notes" defaultValue={relationship.notes ?? ""} /></div>
                  <SubmitButton pendingText="جارٍ الحفظ..." variant="secondary" size="sm" className="w-full sm:w-auto sm:justify-self-start">حفظ العلاقة</SubmitButton>
                </form>
              </Card>
            );
          }) : <EmptyState title="لا توجد علاقات كفالة" description="اربط المتبرع بإحدى الحالات من النموذج أعلاه." />}
        </div>
      </section>

      <section className="mt-8">
        <h2 className="mb-4 text-lg font-black">دفعات المتبرع الشهرية</h2>
        <Card className="overflow-hidden">
          {paymentsResult.data?.length ? (
            <div className="divide-y">
              {paymentsResult.data.map((payment) => {
                const orphan = one(payment.orphans);
                return (
                  <div key={payment.id} className="grid gap-3 px-5 py-4 text-sm sm:grid-cols-[1fr_150px_150px_auto] sm:items-center">
                    <div><p className="font-bold">{orphan?.full_name ?? `حالة ${orphan?.case_number}`}</p><p className="mt-1 text-xs text-[var(--ink-faint)]">{orphan?.case_number}، {formatMonthYear(payment.payment_year, payment.payment_month)}</p></div>
                    <p><span className="text-xs text-[var(--ink-faint)]">المتوقع</span><span className="mt-1 block font-bold">{formatSdg(Number(payment.expected_amount_snapshot))}</span></p>
                    <p><span className="text-xs text-[var(--ink-faint)]">المستلم</span><span className="mt-1 block font-black">{formatSdg(Number(payment.received_amount))}</span></p>
                    <Badge tone={payment.payment_status === "paid" ? "success" : payment.payment_status === "partial" ? "warning" : "danger"}>{paymentStatusLabels[payment.payment_status as keyof typeof paymentStatusLabels]}</Badge>
                  </div>
                );
              })}
            </div>
          ) : <EmptyState title="لا توجد دفعات شهرية" description="لم تسجل دفعات شهرية لهذا المتبرع." />}
        </Card>
      </section>

      <section className="mt-8">
        <h2 className="mb-4 text-lg font-black">تحويلات الأيتام المرتبطة بالمتبرع</h2>
        {transfersResult.data?.length ? (
          <div className="grid gap-4 md:grid-cols-2">
            {transfersResult.data.map((transfer) => {
              const orphan = one(transfer.orphans);
              const receipt = one(transfer.transfer_receipts);
              const asset = one(receipt?.file_assets ?? null);
              return (
                <Card key={transfer.id} className="grid min-w-0 grid-cols-[72px_minmax(0,1fr)] gap-3 p-4 sm:grid-cols-[88px_minmax(0,1fr)] sm:gap-4">
                  {asset ? <SecureImageViewer src={`/api/files/${asset.id}`} alt="إيصال التحويل" mimeType={asset.mime_type} className="aspect-square w-[72px] rounded-md border sm:w-[88px]" /> : <div className="grid aspect-square w-[72px] place-items-center rounded-md border bg-[var(--surface-muted)] px-2 text-center text-[10px] font-bold text-[var(--ink-faint)] sm:w-[88px]">{MISSING_DOCUMENT}</div>}
                  <div className="min-w-0">
                    <div className="flex min-w-0 items-start justify-between gap-2"><p className="min-w-0 break-words font-bold leading-6">{orphan?.full_name ?? `حالة ${orphan?.case_number}`}</p><Badge tone={transfer.status === "paid" ? "success" : "warning"}>{transferStatusLabels[transfer.status as keyof typeof transferStatusLabels]}</Badge></div>
                    <p className="mt-2 break-words font-black">{formatSdg(Number(transfer.amount))}</p>
                    <p className="mt-1 text-xs text-[var(--ink-faint)]">{formatMonthYear(transfer.transfer_year, transfer.transfer_month)}، {formatDate(transfer.transfer_date)}</p>
                  </div>
                </Card>
              );
            })}
          </div>
        ) : <Card><EmptyState title="لا توجد تحويلات" description="لم تسجل تحويلات مرتبطة بهذا المتبرع." /></Card>}
      </section>
    </>
  );
}

function Summary({ label, value }: { label: string; value: string }) {
  return <div className="border-r-4 border-[var(--primary)] bg-white px-5 py-4 shadow-sm"><p className="text-xs font-bold text-[var(--ink-faint)]">{label}</p><p className="mt-2 text-xl font-black">{value}</p></div>;
}
