import Link from "next/link";
import { notFound } from "next/navigation";
import { FileClock, FileImage, Link2, ReceiptText, UsersRound } from "lucide-react";
import {
  createSponsorshipAction,
  deleteOrphanDocumentAction,
  replaceOrphanDocumentAction,
  updateOrphanAction,
  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 { DeleteOrphanForm } from "@/components/forms/delete-orphan-form";
import { ImageUploadField } from "@/components/forms/image-upload-field";
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 { Textarea } from "@/components/ui/textarea";
import { calculateAge, formatSdg } from "@/lib/calculations";
import {
  DEFAULT_MONTHLY_SUPPORT,
  MISSING_DOCUMENT,
  MISSING_VALUE,
  orphanDocumentLabels,
  orphanStatusLabels,
  paymentStatusLabels,
  sponsorshipStatusLabels,
  transferStatusLabels
} from "@/lib/constants";
import { formatDate, formatDateTime, formatMonthYear, todayIso } from "@/lib/dates";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
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;
}

function many<T>(value: Related<T>): T[] {
  if (!value) return [];
  return Array.isArray(value) ? value : [value];
}

const documentTypes = Object.keys(orphanDocumentLabels) as OrphanDocumentType[];

export default async function AdminOrphanDetailsPage({
  params,
  searchParams
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ success?: string; error?: string }>;
}) {
  const { id } = await params;
  const messages = await searchParams;
  const supabase = createAdminSupabaseClient();
  const [orphanResult, documentsResult, relationshipsResult, sponsorsResult, paymentsResult, transfersResult, auditResult] =
    await Promise.all([
      supabase.from("orphans").select("*").eq("id", id).maybeSingle(),
      supabase
        .from("orphan_documents")
        .select("id,title,document_type,created_at,file_assets(id,original_name,extension,mime_type,size_bytes)")
        .eq("orphan_id", id),
      supabase
        .from("sponsorships")
        .select("id,donor_id,monthly_amount,status,start_date,end_date,stop_reason,notes,created_at,profiles!sponsorships_donor_id_fkey(full_name,phone)")
        .eq("orphan_id", id)
        .order("created_at", { ascending: false }),
      supabase.from("profiles").select("id,full_name,phone,is_active").eq("role", "donor").order("full_name"),
      supabase
        .from("sponsor_monthly_payments")
        .select("id,payment_year,payment_month,expected_amount_snapshot,received_amount,payment_status,payment_date,profiles!sponsor_monthly_payments_sponsor_id_fkey(full_name)")
        .eq("orphan_id", id)
        .order("payment_year", { ascending: false })
        .order("payment_month", { ascending: false })
        .limit(200),
      supabase
        .from("orphan_transfers")
        .select("id,transfer_year,transfer_month,amount,transfer_date,status,reference,sponsor_visible_notes,internal_notes,orphan_transfer_sponsors(sponsor_id,profiles!orphan_transfer_sponsors_sponsor_id_fkey(full_name)),transfer_receipts(file_assets(id,original_name,mime_type))")
        .eq("orphan_id", id)
        .order("transfer_year", { ascending: false })
        .order("transfer_month", { ascending: false })
        .limit(200),
      supabase
        .from("audit_logs")
        .select("id,action,metadata,created_at,profiles(full_name)")
        .eq("entity_type", "orphan")
        .eq("entity_id", id)
        .order("created_at", { ascending: false })
        .limit(100)
    ]);
  if (!orphanResult.data) notFound();
  const orphan = orphanResult.data;
  const destination = `/admin/orphans/${id}`;
  const age = calculateAge(orphan.date_of_birth);
  const displayName = orphan.full_name ?? `حالة ${orphan.case_number}`;

  return (
    <>
      <PageHeader
        title={`${orphan.case_number} - ${displayName}`}
        description={
          age === null
            ? "رقم الحالة ثابت ولا يقبل التعديل."
            : `العمر الحالي ${age} سنة، ورقم الحالة ثابت ولا يقبل التعديل.`
        }
        action={
          <Badge tone={orphan.status === "fully_covered" ? "success" : orphan.status === "paused" || orphan.status === "archived" ? "danger" : "info"}>
            {orphanStatusLabels[orphan.status as keyof typeof orphanStatusLabels]}
          </Badge>
        }
      />
      <Notice success={messages.success} error={messages.error} />

      <Card className="p-5 sm:p-6">
        <h2 className="mb-5 text-lg font-black">تعديل بيانات الحالة</h2>
        <form action={updateOrphanAction} className="grid gap-6">
          <input type="hidden" name="id" value={id} />
          <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
            <Field label="رقم الحالة"><Input value={orphan.case_number} readOnly disabled dir="ltr" className="bg-[var(--surface-muted)]" /></Field>
            <Field label="الاسم الكامل"><Input name="fullName" defaultValue={orphan.full_name ?? ""} /></Field>
            <Field label="تاريخ الميلاد (يوم/شهر/سنة)"><Input name="dateOfBirth" type="date" defaultValue={orphan.date_of_birth ?? ""} /></Field>
            <Field label="النوع">
              <select name="gender" defaultValue={orphan.gender ?? ""} className="h-11 w-full rounded-md border bg-white px-3 text-sm">
                <option value="">غير محدد</option>
                <option value="male">ذكر</option>
                <option value="female">أنثى</option>
              </select>
            </Field>
            <Field label="الاحتياج الشهري"><Input name="monthlyNeed" type="number" min={1000} defaultValue={orphan.monthly_need ?? ""} /></Field>
            <Field label="حالة الملف">
              <select name="status" defaultValue={orphan.status} className="h-11 w-full rounded-md border bg-white px-3 text-sm">
                {Object.entries(orphanStatusLabels).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
              </select>
            </Field>
          </div>
          <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
            <Field label="اسم الأم أو ولي الأمر"><Input name="guardianName" defaultValue={orphan.guardian_name ?? ""} /></Field>
            <Field label="صلة المسؤول باليتيم"><Input name="guardianRelationship" defaultValue={orphan.guardian_relationship ?? ""} /></Field>
            <Field label="رقم التواصل"><Input name="guardianPhone" type="tel" dir="ltr" defaultValue={orphan.guardian_phone ?? ""} /></Field>
            <Field label="العنوان"><Input name="address" defaultValue={orphan.address ?? ""} /></Field>
          </div>
          <div className="grid gap-5 sm:grid-cols-3">
            <Field label="اسم البنك"><Input name="bankName" defaultValue={orphan.bank_name ?? ""} /></Field>
            <Field label="اسم صاحب الحساب"><Input name="bankAccountName" defaultValue={orphan.bank_account_name ?? ""} /></Field>
            <Field label="رقم الحساب الكامل"><Input name="bankAccountNumber" dir="ltr" defaultValue={orphan.bank_account_number ?? ""} /></Field>
          </div>
          <div className="grid gap-5 lg:grid-cols-2">
            <Field label="ملاحظات تظهر للمتبرع"><Textarea name="sponsorNotes" defaultValue={orphan.sponsor_notes ?? ""} /></Field>
            <Field label="ملاحظات داخلية للإدارة"><Textarea name="privateNotes" defaultValue={orphan.private_notes ?? ""} /></Field>
          </div>
          <SubmitButton pendingText="جارٍ الحفظ..." className="w-full sm:w-auto sm:justify-self-start">حفظ التعديلات</SubmitButton>
        </form>
      </Card>

      <section className="mt-8">
        <div className="mb-4 flex items-center gap-2"><FileImage size={20} className="text-[var(--primary)]" /><h2 className="text-lg font-black">وثائق الحالة</h2></div>
        <div className="grid gap-5 lg:grid-cols-3">
          {documentTypes.map((type) => {
            const document = documentsResult.data?.find((item) => item.document_type === type);
            const asset = one(document?.file_assets ?? null);
            return (
              <Card key={type} className="overflow-hidden">
                {asset ? (
                  <SecureImageViewer
                    src={`/api/files/${asset.id}`}
                    alt={orphanDocumentLabels[type]}
                    mimeType={asset.mime_type}
                    className="aspect-[16/10] w-full border-b"
                    imageClassName="h-full w-full object-cover"
                  />
                ) : (
                  <div className="grid aspect-[16/10] place-items-center border-b bg-[var(--surface-muted)] px-4 text-center text-sm font-bold text-[var(--ink-faint)]">
                    {MISSING_DOCUMENT}
                  </div>
                )}
                <div className="p-4">
                  <h3 className="font-black">{orphanDocumentLabels[type]}</h3>
                  <p className="mt-1 truncate text-xs text-[var(--ink-faint)]">{asset?.original_name ?? MISSING_DOCUMENT}</p>
                  <form action={replaceOrphanDocumentAction} encType="multipart/form-data" className="mt-4 border-t pt-4">
                    <input type="hidden" name="orphanId" value={id} />
                    <input type="hidden" name="documentType" value={type} />
                    <ImageUploadField id={`file-${type}`} name="file" label={asset ? "صورة بديلة" : "رفع صورة"} required />
                    <SubmitButton pendingText="جارٍ رفع الملف..." size="sm" className="mt-3">
                      {asset ? "استبدال الوثيقة" : "رفع الوثيقة"}
                    </SubmitButton>
                  </form>
                  {asset ? (
                    <ConfirmActionForm
                      action={deleteOrphanDocumentAction}
                      fields={{ orphanId: id, documentType: type }}
                      label="حذف الوثيقة"
                      confirmMessage="هل تريد حذف هذه الوثيقة نهائياً؟"
                      className="mt-3"
                    />
                  ) : null}
                </div>
              </Card>
            );
          })}
        </div>
      </section>

      <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="orphanId" value={id} />
            <input type="hidden" name="returnTo" value={destination} />
            <div className="lg:col-span-2">
              <Label>المتبرع</Label>
              <select name="donorId" required className="h-11 w-full rounded-md border bg-white px-3 text-sm">
                <option value="">اختر المتبرع</option>
                {(sponsorsResult.data ?? []).map((sponsor) => (
                  <option key={sponsor.id} value={sponsor.id} disabled={!sponsor.is_active}>
                    {sponsor.full_name} - {sponsor.phone}
                  </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>

      <section className="mt-8">
        <div className="mb-4 flex items-center gap-2"><UsersRound size={19} className="text-[var(--primary)]" /><h2 className="text-lg font-black">المتبرعون وسجل العلاقات</h2></div>
        <div className="grid gap-4">
          {relationshipsResult.data?.length ? relationshipsResult.data.map((relationship) => {
            const sponsor = one(relationship.profiles);
            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/donors/${relationship.donor_id}`} className="font-black text-[var(--primary)]">{sponsor?.full_name ?? MISSING_VALUE}</Link>
                    <p className="mt-1 text-xs text-[var(--ink-faint)]" dir="ltr">{sponsor?.phone ?? MISSING_VALUE}</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">
        <div className="mb-4 flex items-center gap-2"><ReceiptText size={19} className="text-[var(--primary)]" /><h2 className="text-lg font-black">الحركة المالية المرتبطة بالحالة</h2></div>
        <div className="grid gap-6 xl:grid-cols-2">
          <Card className="overflow-hidden">
            <div className="border-b px-5 py-4"><h3 className="font-black">دفعات المتبرعين</h3></div>
            {paymentsResult.data?.length ? (
              <div className="divide-y">
                {paymentsResult.data.slice(0, 24).map((payment) => {
                  const sponsor = one(payment.profiles);
                  return (
                    <div key={payment.id} className="grid gap-2 px-5 py-4 text-sm sm:grid-cols-[1fr_auto]">
                      <div>
                        <p className="font-bold">{sponsor?.full_name ?? MISSING_VALUE}</p>
                        <p className="mt-1 text-xs text-[var(--ink-faint)]">{formatMonthYear(payment.payment_year, payment.payment_month)}، {formatDate(payment.payment_date)}</p>
                      </div>
                      <div className="sm:text-left">
                        <p className="font-black">{formatSdg(Number(payment.received_amount))}</p>
                        <p className="mt-1 text-xs">{paymentStatusLabels[payment.payment_status as keyof typeof paymentStatusLabels]}</p>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : <EmptyState title="لا توجد دفعات شهرية" description="تظهر بعد إنشاء التزامات المتبرعين الشهرية." />}
          </Card>

          <Card className="overflow-hidden">
            <div className="border-b px-5 py-4"><h3 className="font-black">تحويلات الأيتام</h3></div>
            {transfersResult.data?.length ? (
              <div className="divide-y">
                {transfersResult.data.slice(0, 24).map((transfer) => {
                  const sponsorNames = many(transfer.orphan_transfer_sponsors)
                    .map((link) => one(link.profiles)?.full_name)
                    .filter((name): name is string => Boolean(name));
                  const receipt = one(transfer.transfer_receipts);
                  const asset = one(receipt?.file_assets ?? null);
                  return (
                    <div key={transfer.id} className="grid min-w-0 grid-cols-[72px_minmax(0,1fr)] gap-3 px-4 py-4 text-sm sm:gap-4 sm:px-5">
                      {asset ? (
                        <SecureImageViewer src={`/api/files/${asset.id}`} alt="إيصال التحويل" mimeType={asset.mime_type} className="aspect-square w-[72px] rounded-md border" />
                      ) : <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)]">{MISSING_DOCUMENT}</div>}
                      <div className="min-w-0">
                        <div className="flex flex-wrap justify-between gap-2">
                          <p className="font-bold">{sponsorNames.join("، ") || MISSING_VALUE}</p>
                          <Badge tone={transfer.status === "paid" ? "success" : "warning"}>{transferStatusLabels[transfer.status as keyof typeof transferStatusLabels]}</Badge>
                        </div>
                        <p className="mt-1 text-xs text-[var(--ink-faint)]">{formatMonthYear(transfer.transfer_year, transfer.transfer_month)}، {formatDate(transfer.transfer_date)}</p>
                        <p className="mt-2 font-black">{formatSdg(Number(transfer.amount))}</p>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : <EmptyState title="لا توجد تحويلات" description="تظهر التحويلات الخاصة بهذه الحالة هنا." />}
          </Card>
        </div>
      </section>

      <section className="mt-8">
        <div className="mb-4 flex items-center gap-2"><FileClock size={19} className="text-[var(--primary)]" /><h2 className="text-lg font-black">سجل التدقيق</h2></div>
        <Card className="divide-y overflow-hidden">
          {auditResult.data?.length ? auditResult.data.map((entry) => {
            const actor = one(entry.profiles);
            return (
              <div key={entry.id} className="flex flex-wrap items-center justify-between gap-3 px-5 py-4 text-sm">
                <div><p className="font-bold">{auditLabel(entry.action)}</p><p className="mt-1 text-xs text-[var(--ink-faint)]">{actor?.full_name ?? "النظام"}</p></div>
                <time className="text-xs text-[var(--ink-faint)]">{formatDateTime(entry.created_at)}</time>
              </div>
            );
          }) : <p className="px-5 py-8 text-center text-sm text-[var(--ink-soft)]">لا توجد أحداث تدقيق لهذه الحالة.</p>}
        </Card>
      </section>

      <section className="mt-8">
        <h2 className="mb-4 text-lg font-black text-[var(--danger)]">حذف ملف الحالة</h2>
        <Card className="border-[#e1b6b7] p-5">
          <DeleteOrphanForm orphanId={id} caseNumber={orphan.case_number} orphanName={displayName} />
        </Card>
      </section>
    </>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return <div><Label>{label}</Label>{children}</div>;
}

function auditLabel(action: string) {
  const labels: Record<string, string> = {
    "orphan.created": "إنشاء الحالة",
    "orphan.created_duplicate_override": "إنشاء الحالة بعد تجاوز تحذير التكرار",
    "orphan.updated": "تحديث بيانات الحالة",
    "orphan_document.uploaded": "رفع وثيقة",
    "orphan_document.replaced": "استبدال وثيقة",
    "orphan_document.deleted": "حذف وثيقة",
    "sponsorship.created": "إنشاء علاقة كفالة",
    "sponsorship.updated": "تحديث علاقة كفالة",
    "sponsorship.ended": "إنهاء علاقة كفالة"
  };
  return labels[action] ?? action;
}
