import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { redirect } from "next/navigation";
import { formatDate } from "@/lib/utils";
import { RequestActions } from "./request-actions";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "SuperUser Requests" };

const STATUS_STYLES: Record<string, string> = {
  PENDING: "bg-warning-50 text-warning-700",
  APPROVED: "bg-success-50 text-success-700",
  DENIED: "bg-danger-50 text-danger-700",
};

const ROLE_LABELS: Record<string, string> = {
  TECHNICAL: "Technical",
  MANNING: "Manning",
  ACCOUNTS: "Accounts",
  MANAGER: "Manager",
  SUPERUSER: "SuperUser",
  AUDITOR: "Auditor",
  ADMIN: "Admin",
  SITE_STAFF: "Site Staff",
};

export default async function SuperUserRequestsPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (!hasPermission(session.user.role, "manage_users")) redirect("/dashboard");

  const requests = await db.superUserRequest.findMany({
    include: {
      user: { select: { id: true, name: true, email: true, employeeId: true, role: true } },
      resolvedBy: { select: { name: true } },
    },
    orderBy: [{ status: "asc" }, { createdAt: "desc" }],
  });

  const pending = requests.filter((r) => r.status === "PENDING");
  const resolved = requests.filter((r) => r.status !== "PENDING");

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-neutral-900">SuperUser Access Requests</h1>
          <p className="mt-1 text-sm text-neutral-500">
            {pending.length} pending · {resolved.length} resolved
          </p>
        </div>
      </div>

      {requests.length === 0 && (
        <div className="rounded-lg border border-neutral-200 bg-white p-12 text-center text-neutral-500">
          No SuperUser access requests.
        </div>
      )}

      {pending.length > 0 && (
        <div className="mb-6">
          <h2 className="text-sm font-semibold text-neutral-700 mb-3">Pending</h2>
          <div className="rounded-lg border border-neutral-200 bg-white divide-y divide-neutral-100">
            {pending.map((req) => (
              <div key={req.id} className="p-5">
                <div className="flex items-start justify-between gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="font-medium text-neutral-900">{req.user.name}</span>
                      <span className="font-mono text-xs text-neutral-400">{req.user.employeeId}</span>
                      <span className="rounded-full bg-neutral-100 px-2 py-0.5 text-xs text-neutral-600">
                        {ROLE_LABELS[req.user.role] ?? req.user.role}
                      </span>
                    </div>
                    <p className="text-sm text-neutral-500">{req.user.email}</p>
                    {req.reason && (
                      <p className="mt-2 text-sm text-neutral-700 italic">
                        &ldquo;{req.reason}&rdquo;
                      </p>
                    )}
                    <p className="mt-1 text-xs text-neutral-400">
                      Requested {formatDate(req.createdAt)}
                    </p>
                  </div>
                  <RequestActions requestId={req.id} />
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {resolved.length > 0 && (
        <div>
          <h2 className="text-sm font-semibold text-neutral-700 mb-3">Resolved</h2>
          <div className="rounded-lg border border-neutral-200 bg-white overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-neutral-50 border-b border-neutral-200">
                <tr>
                  <th className="px-4 py-3 text-left font-medium text-neutral-600">User</th>
                  <th className="px-4 py-3 text-left font-medium text-neutral-600">Current Role</th>
                  <th className="px-4 py-3 text-left font-medium text-neutral-600">Status</th>
                  <th className="px-4 py-3 text-left font-medium text-neutral-600">Resolved By</th>
                  <th className="px-4 py-3 text-left font-medium text-neutral-600">Resolved</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {resolved.map((req) => (
                  <tr key={req.id} className="hover:bg-neutral-50">
                    <td className="px-4 py-3">
                      <div className="font-medium text-neutral-900">{req.user.name}</div>
                      <div className="text-xs text-neutral-400">{req.user.email}</div>
                    </td>
                    <td className="px-4 py-3 text-neutral-600">
                      {ROLE_LABELS[req.user.role] ?? req.user.role}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${STATUS_STYLES[req.status] ?? "bg-neutral-100 text-neutral-600"}`}>
                        {req.status.charAt(0) + req.status.slice(1).toLowerCase()}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-neutral-600">{req.resolvedBy?.name ?? "—"}</td>
                    <td className="px-4 py-3 text-neutral-500">
                      {req.resolvedAt ? formatDate(req.resolvedAt) : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
