import Link from "next/link";
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { isAdminEmail, listAdminEmails } from "@/lib/admin";
import { prisma } from "@/lib/prisma";
import type { Prisma } from "@/app/generated/prisma/client";
import { AdminFilterBar } from "@/features/admin/components/admin-filter-bar";

const ENTITY_TYPES = [
  "Refund",
  "Payout",
  "Trip",
  "User",
  "OrganizerVerification",
  "Payment",
] as const;

interface PageProps {
  searchParams: Promise<{
    entityType?: string;
    action?: string;
    reviewer?: string;
    dateFrom?: string;
    dateTo?: string;
  }>;
}

function parseDate(value: string | undefined): Date | undefined {
  if (!value) return undefined;
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? undefined : d;
}

export default async function AdminAuditLogPage({ searchParams }: PageProps) {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login?callbackUrl=/admin/audit-log");
  if (!isAdminEmail(session.user.email)) {
    return (
      <div className="mx-auto max-w-2xl px-4 py-12 text-center">
        <p className="text-sm text-neutral-600">
          Halaman ini hanya untuk admin SeTrip.
        </p>
      </div>
    );
  }

  const params = await searchParams;
  const dateFrom = parseDate(params.dateFrom);
  const dateTo = parseDate(params.dateTo);

  const where: Prisma.AdminActionLogWhereInput = {};
  if (params.entityType && ENTITY_TYPES.includes(params.entityType as never)) {
    where.entityType = params.entityType;
  }
  if (params.action) {
    where.action = { contains: params.action, mode: "insensitive" };
  }
  if (params.reviewer) {
    where.adminEmail = params.reviewer;
  }
  if (dateFrom || dateTo) {
    where.createdAt = {
      ...(dateFrom && { gte: dateFrom }),
      ...(dateTo && { lte: dateTo }),
    };
  }

  const logs = await prisma.adminActionLog.findMany({
    where,
    orderBy: { createdAt: "desc" },
    take: 200,
  });

  return (
    <div className="mx-auto max-w-5xl px-4 py-8 sm:py-12">
      <header className="mb-6">
        <h1 className="text-2xl font-bold text-neutral-900 sm:text-3xl">
          Audit Log
        </h1>
        <p className="mt-1 text-sm text-neutral-500">
          Catatan semua aksi admin lintas entity (refund, payout, trip cancel,
          user suspend, dst). Append-only. Maksimal 200 baris terbaru per query
          — pakai filter untuk drill-down.
        </p>
      </header>

      <AdminFilterBar
        action="/admin/audit-log"
        values={{
          dateFrom: params.dateFrom,
          dateTo: params.dateTo,
          reviewer: params.reviewer,
        }}
        reviewerOptions={listAdminEmails()}
        reviewerLabel="Admin"
      />

      <form method="get" className="mb-4 grid gap-3 sm:grid-cols-2">
        <input type="hidden" name="dateFrom" value={params.dateFrom ?? ""} />
        <input type="hidden" name="dateTo" value={params.dateTo ?? ""} />
        <input type="hidden" name="reviewer" value={params.reviewer ?? ""} />
        <div>
          <label
            htmlFor="filter-entity"
            className="mb-1 block text-[10px] font-semibold uppercase tracking-wide text-neutral-500"
          >
            Entity type
          </label>
          <select
            id="filter-entity"
            name="entityType"
            defaultValue={params.entityType ?? ""}
            className="w-full rounded-lg border border-neutral-200 bg-white px-2 py-1.5 text-sm text-neutral-800 focus:border-primary-400"
          >
            <option value="">Semua</option>
            {ENTITY_TYPES.map((t) => (
              <option key={t} value={t}>
                {t}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label
            htmlFor="filter-action"
            className="mb-1 block text-[10px] font-semibold uppercase tracking-wide text-neutral-500"
          >
            Action (contains)
          </label>
          <div className="flex gap-2">
            <input
              id="filter-action"
              name="action"
              defaultValue={params.action ?? ""}
              placeholder="mis. REFUND, SUSPEND, CANCEL"
              className="flex-1 rounded-lg border border-neutral-200 bg-white px-2 py-1.5 text-sm text-neutral-800 placeholder:text-neutral-400 focus:border-primary-400"
            />
            <button
              type="submit"
              className="rounded-lg bg-primary-600 px-3 py-1.5 text-sm font-semibold text-white hover:bg-primary-700"
            >
              Cari
            </button>
          </div>
        </div>
      </form>

      {logs.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-neutral-300 bg-white p-10 text-center">
          <p className="text-sm text-neutral-500">
            Tidak ada audit log yang cocok dengan filter ini.
          </p>
        </div>
      ) : (
        <div className="overflow-x-auto rounded-2xl border border-neutral-200 bg-white shadow-sm">
          <table className="min-w-full divide-y divide-neutral-100 text-sm">
            <thead className="bg-neutral-50 text-[10px] font-semibold uppercase tracking-wide text-neutral-500">
              <tr>
                <th className="px-3 py-2 text-left">Waktu</th>
                <th className="px-3 py-2 text-left">Admin</th>
                <th className="px-3 py-2 text-left">Action</th>
                <th className="px-3 py-2 text-left">Entity</th>
                <th className="px-3 py-2 text-left">Entity ID</th>
                <th className="px-3 py-2 text-left">Payload</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-100 text-xs text-neutral-700">
              {logs.map((row) => (
                <tr key={row.id}>
                  <td className="whitespace-nowrap px-3 py-2 text-neutral-500">
                    {row.createdAt.toLocaleString("id-ID", {
                      day: "2-digit",
                      month: "short",
                      year: "numeric",
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </td>
                  <td className="whitespace-nowrap px-3 py-2">
                    {row.adminEmail}
                    {!row.adminId && (
                      <span className="ml-1 text-[10px] text-amber-700">
                        (deleted)
                      </span>
                    )}
                  </td>
                  <td className="whitespace-nowrap px-3 py-2">
                    <span className="rounded bg-primary-50 px-1.5 py-0.5 font-mono text-[11px] font-semibold text-primary-800">
                      {row.action}
                    </span>
                  </td>
                  <td className="whitespace-nowrap px-3 py-2 font-medium">
                    {row.entityType}
                  </td>
                  <td className="px-3 py-2">
                    <EntityIdLink
                      entityType={row.entityType}
                      entityId={row.entityId}
                    />
                  </td>
                  <td className="px-3 py-2 text-neutral-500">
                    {row.payload ? (
                      <code className="block max-w-md overflow-x-auto rounded bg-neutral-50 px-2 py-1 font-mono text-[10px]">
                        {JSON.stringify(row.payload)}
                      </code>
                    ) : (
                      "—"
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

function EntityIdLink({
  entityType,
  entityId,
}: {
  entityType: string;
  entityId: string;
}) {
  const short = `${entityId.slice(0, 8)}…`;
  let href: string | null = null;
  if (entityType === "Trip") href = `/admin/trips/${entityId}`;
  if (entityType === "User") href = `/admin/users/${entityId}`;
  if (href) {
    return (
      <Link
        href={href}
        className="font-mono text-[11px] text-secondary-700 hover:text-secondary-900"
      >
        {short}
      </Link>
    );
  }
  return <span className="font-mono text-[11px]">{short}</span>;
}
