import { Search } from "lucide-react";
import {
  deleteTransferAction,
  deleteTransferReceiptAction,
  replaceTransferReceiptAction,
  updateTransferAction
} 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 { ImageUploadField } from "@/components/forms/image-upload-field";
import { SubmitButton } from "@/components/forms/submit-button";
import { TransferCreateForm } from "@/components/forms/transfer-create-form";
import {
  TransferPartyFields,
  type TransferSponsorOption
} from "@/components/forms/transfer-party-fields";
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 { MISSING_DOCUMENT, MISSING_VALUE, transferStatusLabels } from "@/lib/constants";
import { formatDate, formatMonthYear } from "@/lib/dates";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";

type SearchParams = {
  year?: string;
  month?: string;
  sponsor?: string;
  orphan?: string;
  success?: string;
  error?: string;
};

type TransferRow = {
  id: string;
  orphan_id: string;
  transfer_year: number;
  transfer_month: number;
  amount: number;
  transfer_date: string;
  status: "pending" | "paid";
  reference: string | null;
  sponsor_visible_notes: string | null;
  internal_notes: string | null;
  created_at: string;
  orphans: { case_number: string; full_name: string | null } | { case_number: string; full_name: string | null }[] | null;
  orphan_transfer_sponsors:
    | {
        sponsor_id: string;
        profiles: { full_name: string } | { full_name: string }[] | null;
      }
    | {
        sponsor_id: string;
        profiles: { full_name: string } | { full_name: string }[] | null;
      }[]
    | null;
  transfer_receipts:
    | {
        file_assets: { id: string; original_name: string; mime_type: string } | { id: string; original_name: string; mime_type: string }[] | null;
      }
    | {
        file_assets: { id: string; original_name: string; mime_type: string } | { id: string; original_name: string; mime_type: string }[] | null;
      }[]
    | null;
};

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

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

function transferSponsorNames(transfer: TransferRow) {
  return many(transfer.orphan_transfer_sponsors)
    .map((link) => one(link.profiles)?.full_name)
    .filter((name): name is string => Boolean(name));
}

export default async function TransfersPage({ searchParams }: { searchParams: Promise<SearchParams> }) {
  const params = await searchParams;
  const supabase = createAdminSupabaseClient();
  const [relationshipsResult, sponsorsResult, orphansResult] = await Promise.all([
    supabase
      .from("sponsorships")
      .select("id,donor_id,orphan_id,profiles!sponsorships_donor_id_fkey(full_name),orphans(case_number,full_name)")
      .eq("status", "active")
      .limit(1_500),
    supabase.from("profiles").select("id,full_name").eq("role", "donor").order("full_name"),
    supabase.from("orphans").select("id,case_number,full_name").order("case_number")
  ]);

  let transfersQuery = supabase
    .from("orphan_transfers")
    .select("id,orphan_id,transfer_year,transfer_month,amount,transfer_date,status,reference,sponsor_visible_notes,internal_notes,created_at,orphans(case_number,full_name),orphan_transfer_sponsors(sponsor_id,profiles!orphan_transfer_sponsors_sponsor_id_fkey(full_name)),transfer_receipts(file_assets(id,original_name,mime_type))")
    .order("transfer_year", { ascending: false })
    .order("transfer_month", { ascending: false })
    .order("created_at", { ascending: false });
  const year = Number(params.year);
  const month = Number(params.month);
  if (Number.isInteger(year) && year >= 2020 && year <= 2200) transfersQuery = transfersQuery.eq("transfer_year", year);
  if (Number.isInteger(month) && month >= 1 && month <= 12) transfersQuery = transfersQuery.eq("transfer_month", month);
  if (params.orphan && /^[0-9a-f-]{36}$/i.test(params.orphan)) transfersQuery = transfersQuery.eq("orphan_id", params.orphan);
  const { data: transferData } = await transfersQuery.limit(500);
  const allTransfers = (transferData ?? []) as TransferRow[];
  const transfers =
    params.sponsor && /^[0-9a-f-]{36}$/i.test(params.sponsor)
      ? allTransfers.filter((transfer) =>
          many(transfer.orphan_transfer_sponsors).some((link) => link.sponsor_id === params.sponsor)
        )
      : allTransfers;

  const sponsorOptions = new Map<string, TransferSponsorOption>();
  for (const record of relationshipsResult.data ?? []) {
    const sponsor = one(record.profiles);
    const orphan = one(record.orphans);
    const caseNumber = orphan?.case_number ?? MISSING_VALUE;
    const orphanName = orphan?.full_name ?? `حالة ${caseNumber}`;
    const sponsorName = sponsor?.full_name ?? MISSING_VALUE;
    const existing = sponsorOptions.get(record.donor_id);
    if (existing) {
      if (!existing.orphans.some((option) => option.id === record.orphan_id)) {
        existing.orphans.push({ id: record.orphan_id, orphanName, caseNumber });
      }
    } else {
      sponsorOptions.set(record.donor_id, {
        id: record.donor_id,
        sponsorName,
        orphans: [{ id: record.orphan_id, orphanName, caseNumber }]
      });
    }
  }
  const sponsors = [...sponsorOptions.values()]
    .map((sponsor) => ({
      ...sponsor,
      orphans: sponsor.orphans.sort((left, right) => left.caseNumber.localeCompare(right.caseNumber, "ar"))
    }))
    .sort((left, right) => left.sponsorName.localeCompare(right.sponsorName, "ar"));
  const query = new URLSearchParams({
    ...(params.year ? { year: params.year } : {}),
    ...(params.month ? { month: params.month } : {}),
    ...(params.sponsor ? { sponsor: params.sponsor } : {}),
    ...(params.orphan ? { orphan: params.orphan } : {})
  });
  const returnTo = query.size ? `/admin/transfers?${query.toString()}` : "/admin/transfers";

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

      <Card className="mb-6 p-5">
        <form className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
          <div><Label>السنة</Label><Input name="year" type="number" min={2020} max={2200} defaultValue={params.year ?? ""} /></div>
          <div><Label>الشهر</Label><Input name="month" type="number" min={1} max={12} defaultValue={params.month ?? ""} /></div>
          <div>
            <Label>المتبرع</Label>
            <select name="sponsor" defaultValue={params.sponsor ?? ""} 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}>{sponsor.full_name}</option>)}
            </select>
          </div>
          <div>
            <Label>اليتيم</Label>
            <select name="orphan" defaultValue={params.orphan ?? ""} 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>
          <button className="inline-flex h-11 items-center justify-center gap-2 self-end rounded-md border bg-white px-4 text-sm font-bold">
            <Search size={17} aria-hidden /> تصفية
          </button>
        </form>
      </Card>

      <Card className="mb-8 p-5 sm:p-6">
        <h2 className="mb-5 text-lg font-black">إضافة تحويل ليتيم</h2>
        {sponsors.length ? (
          <TransferCreateForm sponsors={sponsors} />
        ) : (
          <EmptyState title="لا توجد علاقات كفالة نشطة" description="اربط اليتيم بمتبرع أولاً من صفحة علاقات الكفالة." />
        )}
      </Card>

      <section>
        <h2 className="mb-4 text-lg font-black">سجل التحويلات</h2>
        {transfers.length ? (
          <div className="grid gap-5 xl:grid-cols-2">
            {transfers.map((transfer) => (
              <TransferCard key={transfer.id} transfer={transfer} returnTo={returnTo} sponsors={sponsors} />
            ))}
          </div>
        ) : <Card><EmptyState title="لا توجد تحويلات مطابقة" description="أضف تحويلاً جديداً أو غيّر عوامل التصفية." /></Card>}
      </section>
    </>
  );
}

function TransferCard({
  transfer,
  returnTo,
  sponsors
}: {
  transfer: TransferRow;
  returnTo: string;
  sponsors: TransferSponsorOption[];
}) {
  const sponsorNames = transferSponsorNames(transfer);
  const linkedSponsorIds = new Set(
    many(transfer.orphan_transfer_sponsors).map((link) => link.sponsor_id)
  );
  const defaultSponsor =
    sponsors.find(
      (sponsor) =>
        linkedSponsorIds.has(sponsor.id) &&
        sponsor.orphans.some((orphan) => orphan.id === transfer.orphan_id)
    ) ??
    sponsors.find((sponsor) =>
      sponsor.orphans.some((orphan) => orphan.id === transfer.orphan_id)
    );
  const orphan = one(transfer.orphans);
  const receipt = one(transfer.transfer_receipts);
  const asset = one(receipt?.file_assets ?? null);
  const orphanName = orphan?.full_name ?? `حالة ${orphan?.case_number}`;

  return (
    <Card className="overflow-hidden">
      <div className="grid min-w-0 grid-cols-[80px_minmax(0,1fr)] gap-3 border-b p-4 sm:grid-cols-[132px_minmax(0,1fr)] sm:gap-4 sm:p-5">
        {asset ? (
          <SecureImageViewer
            src={`/api/files/${asset.id}`}
            alt={`إيصال تحويل ${orphanName}`}
            mimeType={asset.mime_type}
            className="aspect-square w-full rounded-md border"
          />
        ) : (
          <div className="grid aspect-square place-items-center rounded-md border bg-[var(--surface-muted)] px-2 text-center text-xs font-bold text-[var(--ink-faint)]">
            {MISSING_DOCUMENT}
          </div>
        )}
        <div className="min-w-0">
          <div className="flex flex-wrap items-start justify-between gap-2">
            <div className="min-w-0">
              <h3 className="break-words font-black leading-7">{orphanName}</h3>
              <p className="mt-1 break-words text-xs leading-6 text-[var(--ink-faint)]"><span dir="ltr">{orphan?.case_number}</span>، المتبرعون: {sponsorNames.join("، ") || MISSING_VALUE}</p>
            </div>
            <Badge tone={transfer.status === "paid" ? "success" : "warning"}>{transferStatusLabels[transfer.status]}</Badge>
          </div>
          <p className="mt-4 break-words text-lg font-black sm:text-xl">{formatSdg(Number(transfer.amount))}</p>
          <p className="mt-1 text-xs leading-6 text-[var(--ink-soft)]">{formatMonthYear(transfer.transfer_year, transfer.transfer_month)}، تاريخ التحويل {formatDate(transfer.transfer_date)}</p>
          {transfer.sponsor_visible_notes ? <p className="mt-3 line-clamp-2 text-sm leading-6">{transfer.sponsor_visible_notes}</p> : null}
        </div>
      </div>

      <details className="p-4 sm:p-5">
        <summary className="cursor-pointer text-sm font-black text-[var(--primary)]">تعديل التحويل والإيصال</summary>
        <div className="mt-5 grid gap-6">
          <form action={updateTransferAction} className="grid gap-4 sm:grid-cols-2">
            <input type="hidden" name="id" value={transfer.id} />
            <input type="hidden" name="returnTo" value={returnTo} />
            <TransferPartyFields
              sponsors={sponsors}
              idPrefix={`edit-transfer-${transfer.id}`}
              defaultSponsorId={defaultSponsor?.id}
              defaultOrphanId={transfer.orphan_id}
            />
            <div><Label>المبلغ</Label><Input name="amount" type="number" min={0} defaultValue={transfer.amount} required /></div>
            <div><Label>تاريخ التحويل</Label><Input name="transferDate" type="date" defaultValue={transfer.transfer_date} required /></div>
            <div><Label>مرجع العملية</Label><Input name="reference" defaultValue={transfer.reference ?? ""} /></div>
            <div><Label>ملاحظة تظهر للمتبرع</Label><Input name="sponsorVisibleNotes" defaultValue={transfer.sponsor_visible_notes ?? ""} /></div>
            <div><Label>ملاحظة داخلية</Label><Input name="internalNotes" defaultValue={transfer.internal_notes ?? ""} /></div>
            <SubmitButton pendingText="جارٍ حفظ التعديل..." size="sm" className="w-full sm:w-auto sm:justify-self-start">حفظ التعديل</SubmitButton>
          </form>

          <div className="border-t pt-5">
            <form action={replaceTransferReceiptAction} encType="multipart/form-data" className="grid gap-3">
              <input type="hidden" name="transferId" value={transfer.id} />
              <input type="hidden" name="returnTo" value={returnTo} />
              <ImageUploadField name="receipt" id={`receipt-${transfer.id}`} label={asset ? "استبدال صورة الإيصال" : "رفع صورة الإيصال"} required />
              <SubmitButton pendingText="جارٍ رفع الملف..." size="sm" className="w-full sm:w-auto sm:justify-self-start">
                {asset ? "استبدال الإيصال" : "رفع الإيصال"}
              </SubmitButton>
            </form>
            <div className="mt-3 flex flex-wrap gap-2">
              {asset ? (
                <ConfirmActionForm
                  action={deleteTransferReceiptAction}
                  fields={{ transferId: transfer.id, returnTo }}
                  label="حذف الإيصال"
                  confirmMessage="هل تريد حذف الإيصال؟ سيعود التحويل إلى قيد الانتظار."
                />
              ) : null}
              <ConfirmActionForm
                action={deleteTransferAction}
                fields={{ id: transfer.id, returnTo }}
                label="حذف التحويل"
                confirmMessage="هل تريد حذف التحويل وإيصاله نهائياً؟"
              />
            </div>
          </div>
        </div>
      </details>
    </Card>
  );
}
