import { notFound } from "next/navigation";
import { FileImage, Landmark, ReceiptText } from "lucide-react";
import { PageHeader } from "@/components/dashboard/page-header";
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 { calculateAge, formatSdg } from "@/lib/calculations";
import { requireProfile } from "@/lib/auth";
import {
  MISSING_DOCUMENT,
  MISSING_VALUE,
  orphanDocumentLabels,
  orphanStatusLabels,
  sponsorshipStatusLabels,
  transferStatusLabels
} from "@/lib/constants";
import { formatDate, formatMonthYear } from "@/lib/dates";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import type { OrphanDocumentType } from "@/types/domain";

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 SponsorOrphanDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const profile = await requireProfile("donor");
  const supabase = await createServerSupabaseClient();
  const [orphanResult, relationshipResult, documentsResult, transfersResult] = await Promise.all([
    supabase.from("orphans").select("*").eq("id", id).maybeSingle(),
    supabase
      .from("sponsorships")
      .select("id,monthly_amount,start_date,end_date,status,notes")
      .eq("orphan_id", id)
      .eq("donor_id", profile.id)
      .eq("status", "active")
      .maybeSingle(),
    supabase
      .from("orphan_documents")
      .select("id,title,document_type,created_at,file_assets(id,original_name,mime_type,size_bytes)")
      .eq("orphan_id", id),
    supabase
      .from("orphan_transfers")
      .select("id,transfer_year,transfer_month,amount,transfer_date,status,sponsor_visible_notes,transfer_receipts(file_assets(id,mime_type))")
      .eq("orphan_id", id)
      .order("transfer_year", { ascending: false })
      .order("transfer_month", { ascending: false })
      .limit(60)
  ]);
  if (!orphanResult.data || !relationshipResult.data) notFound();
  const orphan = orphanResult.data;
  const relationship = relationshipResult.data;
  const age = calculateAge(orphan.date_of_birth);
  const displayName = orphan.full_name ?? `حالة ${orphan.case_number}`;

  return (
    <>
      <PageHeader
        title={`${orphan.case_number} - ${displayName}`}
        description={
          orphan.date_of_birth
            ? `تاريخ الميلاد ${formatDate(orphan.date_of_birth)}${age === null ? "" : `، العمر الحالي ${age} سنة`}`
            : "تاريخ الميلاد غير متوفر"
        }
        action={<Badge tone="info">{orphanStatusLabels[orphan.status as keyof typeof orphanStatusLabels]}</Badge>}
      />

      <div className="grid gap-6 xl:grid-cols-[1.2fr_.8fr]">
        <div className="space-y-6">
          <Card className="p-5">
            <h2 className="font-black">بيانات الحالة</h2>
            <dl className="mt-4 grid gap-x-6 sm:grid-cols-2">
              <Item label="رقم الحالة" value={orphan.case_number} />
              <Item label="الاسم الكامل" value={orphan.full_name} />
              <Item label="تاريخ الميلاد" value={orphan.date_of_birth ? formatDate(orphan.date_of_birth) : null} />
              <Item label="العمر" value={age === null ? null : `${age} سنة`} />
              <Item label="النوع" value={orphan.gender ? (orphan.gender === "male" ? "ذكر" : "أنثى") : null} />
              <Item label="الأم أو ولي الأمر" value={orphan.guardian_name} />
              <Item label="صلة المسؤول باليتيم" value={orphan.guardian_relationship} />
              <Item label="رقم التواصل" value={orphan.guardian_phone} />
              <Item label="العنوان" value={orphan.address} />
            </dl>
            {orphan.sponsor_notes ? <div className="mt-4 border-t pt-4"><p className="text-xs font-bold text-[var(--ink-faint)]">ملاحظات الحالة</p><p className="mt-2 whitespace-pre-wrap text-sm leading-7">{orphan.sponsor_notes}</p></div> : null}
          </Card>

          <Card className="overflow-hidden">
            <div className="flex items-center gap-2 border-b px-5 py-4"><FileImage size={18} className="text-[var(--primary)]" /><h2 className="font-black">وثائق الحالة</h2></div>
            <div className="grid gap-5 p-5 md:grid-cols-3">
              {(Object.keys(orphanDocumentLabels) as OrphanDocumentType[]).map((type) => {
                const document = documentsResult.data?.find((item) => item.document_type === type);
                const asset = one(document?.file_assets ?? null);
                return (
                  <div key={type} className="overflow-hidden rounded-md border">
                    {asset ? (
                      <SecureImageViewer
                        src={`/api/files/${asset.id}`}
                        alt={orphanDocumentLabels[type]}
                        mimeType={asset.mime_type}
                        className="aspect-[4/3] w-full"
                      />
                    ) : <div className="grid aspect-[4/3] place-items-center bg-[var(--surface-muted)] px-3 text-center text-xs font-bold text-[var(--ink-faint)]">{MISSING_DOCUMENT}</div>}
                    <p className="p-3 text-sm font-bold">{orphanDocumentLabels[type]}</p>
                  </div>
                );
              })}
            </div>
          </Card>
        </div>

        <div className="space-y-6">
          <Card className="p-5">
            <h2 className="font-black">علاقة الكفالة</h2>
            <dl className="mt-4">
              <Item label="مساهمتك الشهرية" value={formatSdg(Number(relationship.monthly_amount))} />
              <Item label="تاريخ البداية" value={formatDate(relationship.start_date)} />
              <Item label="حالة العلاقة" value={sponsorshipStatusLabels[relationship.status as keyof typeof sponsorshipStatusLabels]} />
              <Item label="الاحتياج الشهري للحالة" value={orphan.monthly_need == null ? null : formatSdg(Number(orphan.monthly_need))} />
            </dl>
          </Card>
          <Card className="p-5">
            <div className="flex items-center gap-2"><Landmark size={19} className="text-[var(--primary)]" /><h2 className="font-black">بيانات الحساب البنكي</h2></div>
            <dl className="mt-4">
              <Item label="اسم البنك" value={orphan.bank_name} />
              <Item label="اسم صاحب الحساب" value={orphan.bank_account_name} />
              <Item label="رقم الحساب الكامل" value={orphan.bank_account_number} />
            </dl>
          </Card>
        </div>
      </div>

      <section className="mt-8">
        <div className="mb-4 flex items-center gap-2"><ReceiptText size={19} className="text-[var(--primary)]" /><h2 className="text-lg font-black">سجل دفعاتك الشهرية</h2></div>
        {transfersResult.data?.length ? (
          <div className="grid gap-4 md:grid-cols-2">
            {transfersResult.data.map((transfer) => {
              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-[92px_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-[92px]" /> : <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-[92px] sm:text-xs">{MISSING_DOCUMENT}</div>}
                  <div className="min-w-0">
                    <div className="flex min-w-0 flex-wrap items-start justify-between gap-2"><p className="break-words font-bold">{formatMonthYear(transfer.transfer_year, transfer.transfer_month)}</p><Badge tone={transfer.status === "paid" ? "success" : "warning"}>{transferStatusLabels[transfer.status as keyof typeof transferStatusLabels]}</Badge></div>
                    <p className="mt-2 break-words text-base font-black sm:text-lg">{formatSdg(Number(transfer.amount))}</p>
                    <p className="mt-1 text-xs text-[var(--ink-faint)]">{formatDate(transfer.transfer_date)}</p>
                    {transfer.sponsor_visible_notes ? <p className="mt-2 line-clamp-2 text-xs leading-6">{transfer.sponsor_visible_notes}</p> : null}
                  </div>
                </Card>
              );
            })}
          </div>
        ) : <Card><EmptyState title="لا توجد تحويلات شهرية" description="تظهر تحويلات الأيتام المرتبطة بك فقط." /></Card>}
      </section>
    </>
  );
}

function Item({ label, value }: { label: string; value: string | null | undefined }) {
  return <div className="border-b py-3"><dt className="text-xs font-bold text-[var(--ink-faint)]">{label}</dt><dd className="mt-1 break-words text-sm font-semibold">{value || MISSING_VALUE}</dd></div>;
}
