import { createNotificationAction } from "@/app/actions/admin";
import { Notice } from "@/components/dashboard/notice";
import { PageHeader } from "@/components/dashboard/page-header";
import { SubmitButton } from "@/components/forms/submit-button";
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 { createAdminSupabaseClient } from "@/lib/supabase/admin";
import { formatDateTime } from "@/lib/dates";

export default async function NotificationsPage({ searchParams }: { searchParams: Promise<{ success?: string; error?: string }> }) {
  const messages = await searchParams;
  const supabase = createAdminSupabaseClient();
  const [notifications, donors] = await Promise.all([
    supabase
      .from("notifications")
      .select("id,title,body,read_at,created_at,profiles(full_name)")
      .order("created_at", { ascending: false })
      .limit(100),
    supabase.from("profiles").select("id,full_name").eq("role", "donor").eq("is_active", true).order("full_name")
  ]);
  return (
    <>
      <PageHeader title="الإشعارات" description="إرسال إشعارات داخلية للمتبرعين ومتابعة وقت القراءة." />
      <Notice success={messages.success} error={messages.error} />
      <Card className="mb-6 p-5">
        <h2 className="mb-4 font-black">إشعار جديد</h2>
        <form action={createNotificationAction} className="grid gap-5 md:grid-cols-2">
          <div>
            <Label>المستلم</Label>
            <select name="recipientId" required className="h-11 w-full rounded-md border bg-white px-3 text-sm">
              <option value="">اختر المتبرع</option>{donors.data?.map((donor) => <option key={donor.id} value={donor.id}>{donor.full_name}</option>)}
            </select>
          </div>
          <div><Label>العنوان</Label><Input name="title" required /></div>
          <div className="md:col-span-2"><Label>النص</Label><Textarea name="body" required /></div>
          <div><Label>رابط داخل المنصة (اختياري)</Label><Input name="link" placeholder="/donor/transfers" dir="ltr" /></div>
          <SubmitButton pendingText="جارٍ إرسال الإشعار..." className="w-full sm:w-auto sm:justify-self-start">إرسال الإشعار</SubmitButton>
        </form>
      </Card>
      <Card className="overflow-hidden">
        {notifications.data?.length ? (
          <div className="divide-y">
            {notifications.data.map((notification) => {
              const profile = notification.profiles as { full_name: string } | { full_name: string }[] | null;
              return (
                <div key={notification.id} className="grid gap-2 px-5 py-4 md:grid-cols-[180px_1fr_120px]">
                  <div><p className="text-sm font-bold">{Array.isArray(profile) ? profile[0]?.full_name : profile?.full_name}</p><p className="mt-1 text-xs text-[var(--ink-faint)]">{formatDateTime(notification.created_at)}</p></div>
                  <div><p className="text-sm font-bold">{notification.title}</p><p className="mt-1 text-sm leading-7 text-[var(--ink-soft)]">{notification.body}</p></div>
                  <span className="text-xs font-bold text-[var(--ink-faint)]">{notification.read_at ? "تمت القراءة" : "غير مقروء"}</span>
                </div>
              );
            })}
          </div>
        ) : <EmptyState title="لا توجد إشعارات" description="أرسل إشعاراً للمتبرع من النموذج أعلاه." />}
      </Card>
    </>
  );
}
