import Link from "next/link";
import { Check } from "lucide-react";
import { markNotificationReadAction } from "@/app/actions/donor";
import { PageHeader } from "@/components/dashboard/page-header";
import { Card } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { requireProfile } from "@/lib/auth";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import { formatDateTime } from "@/lib/dates";
import { SubmitButton } from "@/components/forms/submit-button";

export default async function DonorNotificationsPage() {
  const profile = await requireProfile("donor");
  const supabase = await createServerSupabaseClient();
  const { data } = await supabase
    .from("notifications")
    .select("id,title,body,link,read_at,created_at")
    .eq("recipient_id", profile.id)
    .order("created_at", { ascending: false });
  return (
    <>
      <PageHeader title="الإشعارات" description="رسائل الإدارة والتحديثات المرتبطة بالكفالة والتحويلات." />
      <Card className="overflow-hidden">
        {data?.length ? (
          <div className="divide-y">
            {data.map((notification) => (
              <article key={notification.id} className={`flex min-w-0 gap-3 px-4 py-4 sm:gap-4 sm:px-5 sm:py-5 ${notification.read_at ? "bg-white" : "bg-[#f0f7f6]"}`}>
                <div className="min-w-0 flex-1">
                  <h2 className="text-sm font-black">{notification.title}</h2>
                  <p className="mt-2 text-sm leading-7 text-[var(--ink-soft)]">{notification.body}</p>
                  <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs">
                    <time className="text-[var(--ink-faint)]">{formatDateTime(notification.created_at)}</time>
                    {notification.link ? <Link href={notification.link} className="font-bold text-[var(--primary)]">فتح الرابط</Link> : null}
                  </div>
                </div>
                {!notification.read_at ? (
                  <form action={markNotificationReadAction}>
                    <input type="hidden" name="id" value={notification.id} />
                    <SubmitButton pendingText="" size="icon" variant="secondary" className="size-9" title="تحديد كمقروء"><Check size={16} /></SubmitButton>
                  </form>
                ) : null}
              </article>
            ))}
          </div>
        ) : <EmptyState title="لا توجد إشعارات" description="ستظهر تحديثات الإدارة هنا." />}
      </Card>
    </>
  );
}
