import Link from "next/link";
import { Search } 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 { 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 { createServerSupabaseClient } from "@/lib/supabase/server";

type SearchParams = { year?: string; month?: string };

type TransferRow = {
  id: string;
  transfer_year: number;
  transfer_month: number;
  amount: number;
  transfer_date: string;
  status: "pending" | "paid";
  sponsor_visible_notes: string | null;
  orphans: { id: string; case_number: string; full_name: string | null } | { id: string; case_number: string; full_name: string | null }[] | null;
  transfer_receipts:
    | {
        file_assets: { id: string; mime_type: string } | { id: string; mime_type: string }[] | null;
      }
    | {
        file_assets: { id: string; mime_type: string } | { id: string; mime_type: string }[] | null;
      }[]
    | null;
};

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

export default async function SponsorTransfersPage({ searchParams }: { searchParams: Promise<SearchParams> }) {
  const params = await searchParams;
  const supabase = await createServerSupabaseClient();
  let query = supabase
    .from("orphan_transfers")
    .select("id,transfer_year,transfer_month,amount,transfer_date,status,sponsor_visible_notes,orphans(id,case_number,full_name),transfer_receipts(file_assets(id,mime_type))")
    .order("transfer_year", { ascending: false })
    .order("transfer_month", { ascending: false })
    .order("transfer_date", { ascending: false });
  const year = Number(params.year);
  const month = Number(params.month);
  if (Number.isInteger(year) && year >= 2020 && year <= 2200) query = query.eq("transfer_year", year);
  if (Number.isInteger(month) && month >= 1 && month <= 12) query = query.eq("transfer_month", month);
  const { data } = await query.range(0, 99);
  const transfers = (data ?? []) as TransferRow[];

  return (
    <>
      <PageHeader title="التحويلات والإيصالات" description="الأموال المحولة إلى الحالات المرتبطة بك، مع إيصال كل تحويل وملاحظته." />

      <Card className="mb-6 p-4">
        <form className="grid gap-3 sm:grid-cols-[160px_140px_auto]">
          <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>
          <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>

      {transfers.length ? (
        <>
          <div className="grid gap-4 xl:hidden">
            {transfers.map((transfer) => <MobileTransferCard key={transfer.id} transfer={transfer} />)}
          </div>
          <Card className="hidden overflow-hidden xl:block">
            <div className="table-scroll">
              <table className="w-full min-w-[850px] 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">ملاحظة</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {transfers.map((transfer) => {
                    const orphan = one(transfer.orphans);
                    const receipt = one(transfer.transfer_receipts);
                    const asset = one(receipt?.file_assets ?? null);
                    return (
                      <tr key={transfer.id}>
                        <td className="px-4 py-3 font-bold">{formatMonthYear(transfer.transfer_year, transfer.transfer_month)}</td>
                        <td className="px-4 py-3"><Link href={`/donor/orphans/${orphan?.id}`} className="font-bold text-[var(--primary)]">{orphan?.full_name ?? `حالة ${orphan?.case_number}`}<span className="mt-1 block text-xs text-[var(--ink-faint)]" dir="ltr">{orphan?.case_number}</span></Link></td>
                        <td className="px-4 py-3 font-black">{formatSdg(Number(transfer.amount))}</td>
                        <td className="px-4 py-3">{formatDate(transfer.transfer_date)}</td>
                        <td className="px-4 py-3"><TransferBadge status={transfer.status} /></td>
                        <td className="px-4 py-3">
                          {asset ? <SecureImageViewer src={`/api/files/${asset.id}`} alt="إيصال التحويل" mimeType={asset.mime_type} className="size-16 rounded-md border" /> : MISSING_DOCUMENT}
                        </td>
                        <td className="max-w-[260px] px-4 py-3 leading-7">{transfer.sponsor_visible_notes ?? MISSING_VALUE}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>
        </>
      ) : <Card><EmptyState title="لا توجد تحويلات" description="تظهر هنا التحويلات المرتبطة بحسابك فقط." /></Card>}
    </>
  );
}

function MobileTransferCard({ transfer }: { transfer: TransferRow }) {
  const orphan = one(transfer.orphans);
  const receipt = one(transfer.transfer_receipts);
  const asset = one(receipt?.file_assets ?? null);
  return (
    <Card className="overflow-hidden">
      <div className="grid min-w-0 grid-cols-[80px_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-20 rounded-md border sm:w-[92px]" />
        ) : (
          <div className="grid aspect-square w-20 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 items-start justify-between gap-2">
            <div className="min-w-0">
              <h2 className="break-words font-black leading-7">{orphan?.full_name ?? `حالة ${orphan?.case_number}`}</h2>
              <p className="mt-1 text-xs text-[var(--ink-faint)]" dir="ltr">{orphan?.case_number ?? MISSING_VALUE}</p>
            </div>
            <TransferBadge status={transfer.status} />
          </div>
          <p className="mt-3 break-words text-lg font-black sm:text-xl">{formatSdg(Number(transfer.amount))}</p>
        </div>
      </div>
      <dl className="grid grid-cols-2 gap-4 border-t p-4 text-sm">
        <div><dt className="text-xs text-[var(--ink-faint)]">الشهر</dt><dd className="mt-1 font-bold">{formatMonthYear(transfer.transfer_year, transfer.transfer_month)}</dd></div>
        <div><dt className="text-xs text-[var(--ink-faint)]">تاريخ التحويل</dt><dd className="mt-1 font-bold">{formatDate(transfer.transfer_date)}</dd></div>
      </dl>
      {transfer.sponsor_visible_notes ? <p className="border-t px-4 py-3 text-sm leading-7">{transfer.sponsor_visible_notes}</p> : null}
    </Card>
  );
}

function TransferBadge({ status }: { status: TransferRow["status"] }) {
  return <Badge tone={status === "paid" ? "success" : "warning"}>{transferStatusLabels[status]}</Badge>;
}
