import { PageHeader } from "@/components/dashboard/page-header";
import { Card } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
import { formatDateTime } from "@/lib/dates";

export default async function AuditPage() {
  const supabase = createAdminSupabaseClient();
  const { data } = await supabase
    .from("audit_logs")
    .select("id,action,entity_type,entity_id,ip_address,created_at,profiles(full_name)")
    .order("created_at", { ascending: false })
    .limit(300);
  const entries = (data ?? []).map((entry) => {
    const profile = entry.profiles as { full_name: string } | { full_name: string }[] | null;
    return {
      ...entry,
      profileName: Array.isArray(profile) ? profile[0]?.full_name : profile?.full_name ?? "النظام/زائر"
    };
  });
  return (
    <>
      <PageHeader title="سجل التدقيق" description="سجل زمني للعمليات الحساسة، بما فيها الوصول إلى الملفات ومحاولات الوصول المرفوضة." />
      {entries.length ? (
        <>
          <div className="grid gap-3 xl:hidden">
            {entries.map((entry) => (
              <Card key={entry.id} className="min-w-0 p-4">
                <div className="flex flex-wrap items-start justify-between gap-2">
                  <p className="min-w-0 break-all font-black leading-6" dir="ltr">{entry.action}</p>
                  <time className="text-xs leading-6 text-[var(--ink-faint)]">{formatDateTime(entry.created_at)}</time>
                </div>
                <dl className="mt-3 grid gap-2 border-t pt-3 text-sm">
                  <div className="flex flex-wrap justify-between gap-2"><dt className="text-[var(--ink-soft)]">المستخدم</dt><dd className="font-bold">{entry.profileName}</dd></div>
                  <div className="flex flex-wrap justify-between gap-2"><dt className="text-[var(--ink-soft)]">الكيان</dt><dd className="min-w-0 break-all" dir="ltr">{entry.entity_type}</dd></div>
                  <div className="grid gap-1"><dt className="text-[var(--ink-soft)]">المعرّف</dt><dd className="break-all text-xs leading-6" dir="ltr">{entry.entity_id}</dd></div>
                  <div className="flex flex-wrap justify-between gap-2"><dt className="text-[var(--ink-soft)]">العنوان الشبكي</dt><dd dir="ltr">{entry.ip_address ?? "—"}</dd></div>
                </dl>
              </Card>
            ))}
          </div>
          <Card className="hidden overflow-hidden xl:block">
            <div className="table-scroll">
              <table className="w-full min-w-[820px] 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></tr>
              </thead>
              <tbody className="divide-y">
                {entries.map((entry) => (
                    <tr key={entry.id}>
                      <td className="px-4 py-3">{formatDateTime(entry.created_at)}</td>
                      <td className="px-4 py-3">{entry.profileName}</td>
                      <td className="px-4 py-3 font-bold" dir="ltr">{entry.action}</td>
                      <td className="px-4 py-3" dir="ltr">{entry.entity_type}</td>
                      <td className="max-w-44 truncate px-4 py-3" dir="ltr">{entry.entity_id}</td>
                      <td className="px-4 py-3" dir="ltr">{entry.ip_address ?? "—"}</td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
          </Card>
        </>
      ) : <Card><EmptyState title="سجل التدقيق فارغ" description="ستظهر الأحداث الحساسة هنا بعد بدء استخدام المنصة." /></Card>}
    </>
  );
}
