import Link from "next/link";
import { ArrowLeft, Plus, Search } from "lucide-react";
import { Notice } from "@/components/dashboard/notice";
import { PageHeader } from "@/components/dashboard/page-header";
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 { calculateAge, formatSdg } from "@/lib/calculations";
import { MISSING_VALUE, orphanStatusLabels } from "@/lib/constants";
import { formatDate } from "@/lib/dates";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";

type Props = {
  searchParams: Promise<{ q?: string; status?: string; success?: string; error?: string }>;
};

export default async function AdminOrphansPage({ searchParams }: Props) {
  const params = await searchParams;
  const supabase = createAdminSupabaseClient();
  const query = params.q?.trim().replace(/[,%()]/g, "");
  let request = supabase
    .from("orphans")
    .select("id,case_number,full_name,date_of_birth,monthly_need,covered_amount,status,created_at")
    .order("created_at", { ascending: false })
    .limit(200);
  if (query) request = request.or(`case_number.ilike.%${query}%,full_name.ilike.%${query}%`);
  if (params.status && params.status in orphanStatusLabels) request = request.eq("status", params.status);
  const { data } = await request;

  return (
    <>
      <PageHeader
        title="إدارة حالات الأيتام"
        description="بحث الحالات وإدارة بياناتها ووثائقها ومتبرعيها وسجل تحويلاتها."
        action={
          <Link href="/admin/orphans/new" className="inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-md bg-[var(--primary)] px-4 py-2 text-sm font-bold text-white sm:w-auto">
            <Plus size={17} aria-hidden />
            إضافة حالة جديدة
          </Link>
        }
      />
      <Notice success={params.success} error={params.error} />

      <form className="mb-5 grid gap-3 sm:grid-cols-[minmax(0,1fr)_220px_auto]">
        <Input name="q" defaultValue={params.q} placeholder="رقم الحالة أو الاسم" />
        <select name="status" defaultValue={params.status ?? ""} className="h-11 rounded-md border bg-white px-3 text-sm">
          <option value="">جميع الحالات</option>
          {Object.entries(orphanStatusLabels).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
        </select>
        <button className="inline-flex h-11 items-center justify-center gap-2 rounded-md border bg-white px-4 text-sm font-bold">
          <Search size={17} aria-hidden />
          بحث
        </button>
      </form>

      <Card className="overflow-hidden">
        {data?.length ? (
          <>
          <div className="divide-y xl:hidden">
            {data.map((orphan) => {
              const age = calculateAge(orphan.date_of_birth);
              return (
                <article key={orphan.id} className="p-4">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="text-xs font-extrabold text-[var(--ink-faint)]" dir="ltr">{orphan.case_number}</p>
                      <h2 className="mt-1 truncate font-black">{orphan.full_name ?? `حالة ${orphan.case_number}`}</h2>
                    </div>
                    <Badge tone={orphan.status === "fully_covered" ? "success" : orphan.status === "paused" || orphan.status === "archived" ? "danger" : "info"}>
                      {orphanStatusLabels[orphan.status as keyof typeof orphanStatusLabels]}
                    </Badge>
                  </div>
                  <dl className="mt-4 grid grid-cols-2 gap-3 text-sm">
                    <div className="min-w-0"><dt className="text-xs text-[var(--ink-faint)]">العمر</dt><dd className="mt-1 break-words font-bold">{age === null ? MISSING_VALUE : `${age} سنة`}</dd></div>
                    <div className="min-w-0"><dt className="text-xs text-[var(--ink-faint)]">الاحتياج الشهري</dt><dd className="mt-1 break-words font-bold">{orphan.monthly_need == null ? MISSING_VALUE : formatSdg(Number(orphan.monthly_need))}</dd></div>
                    <div className="min-w-0"><dt className="text-xs text-[var(--ink-faint)]">تاريخ الإضافة</dt><dd className="mt-1 break-words font-bold">{formatDate(orphan.created_at)}</dd></div>
                  </dl>
                  <Link href={`/admin/orphans/${orphan.id}`} className="mt-4 inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-md border px-3 py-2 text-sm font-bold text-[var(--primary)] sm:w-auto">
                    التفاصيل <ArrowLeft size={15} aria-hidden />
                  </Link>
                </article>
              );
            })}
          </div>
          <div className="table-scroll hidden xl:block">
            <table className="w-full min-w-[800px] 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"><span className="sr-only">عرض</span></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[var(--border)]">
                {data.map((orphan) => (
                  <tr key={orphan.id}>
                    <td className="px-4 py-3 font-extrabold" dir="ltr">{orphan.case_number}</td>
                    <td className="px-4 py-3 font-bold">{orphan.full_name ?? `حالة ${orphan.case_number}`}</td>
                    <td className="px-4 py-3">{calculateAge(orphan.date_of_birth) === null ? MISSING_VALUE : `${calculateAge(orphan.date_of_birth)} سنة`}</td>
                    <td className="px-4 py-3">{orphan.monthly_need == null ? MISSING_VALUE : formatSdg(Number(orphan.monthly_need))}</td>
                    <td className="px-4 py-3">{formatSdg(Number(orphan.covered_amount))}</td>
                    <td className="px-4 py-3">
                      <Badge tone={orphan.status === "fully_covered" ? "success" : orphan.status === "paused" || orphan.status === "archived" ? "danger" : "info"}>
                        {orphanStatusLabels[orphan.status as keyof typeof orphanStatusLabels]}
                      </Badge>
                    </td>
                    <td className="px-4 py-3">
                      <Link href={`/admin/orphans/${orphan.id}`} className="inline-flex items-center gap-1 font-bold text-[var(--primary)]">
                        التفاصيل <ArrowLeft size={15} aria-hidden />
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          </>
        ) : (
          <EmptyState title="لا توجد حالات مطابقة" description="أضف حالة جديدة أو عدّل عبارة البحث والتصفية." />
        )}
      </Card>
    </>
  );
}
