import type { Metadata } from "next";
import Link from "next/link";
import CustomerAdminShell from "../CustomerAdminShell";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

import { prisma } from "@/lib/prisma";
import { AUTH_COOKIE_NAME } from "@/lib/auth/constants";

import {
  hashSessionToken,
  isValidSessionTokenFormat,
} from "@/lib/auth/session-token";

import {
  hasPermission,
  loadAuthorizationForUser,
} from "@/lib/auth/authorization";

export const metadata: Metadata = {
  title: "Lead Management | Teja Technology CRM",
  robots: {
    index: false,
    follow: false,
  },
};

export const dynamic = "force-dynamic";

export default async function AdminLeadsPage() {
  const cookieStore = await cookies();

  const token =
    cookieStore.get(AUTH_COOKIE_NAME)?.value;

  if (
    !token ||
    !isValidSessionTokenFormat(token)
  ) {
    redirect("/admin/login");
  }

  const session = await prisma.authSession.findUnique({
    where: {
      tokenHash: hashSessionToken(token),
    },
    select: {
      userId: true,
      expiresAt: true,
      revokedAt: true,
    },
  });

  if (
    !session ||
    session.revokedAt !== null ||
    session.expiresAt.getTime() <= Date.now()
  ) {
    redirect("/admin/login");
  }

  const authorization =
    await loadAuthorizationForUser(session.userId);

  if (
    !authorization ||
    authorization.status !== "ACTIVE" ||
    !authorization.roles.includes("SUPER_ADMIN")
  ) {
    redirect("/admin/login");
  }

  if (authorization.mustChangePassword) {
    redirect("/admin/change-password");
  }

  if (!hasPermission(authorization, "LEAD_VIEW")) {
    redirect("/admin");
  }

  const [totalLeads, leads] = await Promise.all([
    prisma.lead.count(),

    prisma.lead.findMany({
      orderBy: [
        { createdAt: "desc" },
        { id: "desc" },
      ],
      take: 25,
      select: {
        id: true,
        leadCode: true,
        name: true,
        companyName: true,
        service: true,
        source: true,
        status: true,
        createdAt: true,
        assignedTo: {
          select: {
            name: true,
          },
        },
      },
    }),
  ]);

  return (
    <CustomerAdminShell>
    <main className="min-h-[75vh] bg-[var(--soft)] px-5 py-14">
      <div className="container">
        <div className="mb-8 flex flex-wrap items-start justify-between gap-4">
          <div>
            <p className="mb-2 text-xs font-bold uppercase tracking-[0.18em] text-[var(--blue)]">
              Teja Technology CRM
            </p>

            <h1 className="text-3xl font-bold text-[var(--navy)]">
              Lead Management
            </h1>

            <p className="mt-2 text-sm text-[var(--muted)]">
              View and manage incoming business enquiries.
            </p>
          </div>

          <Link
            href="/admin"
            className="rounded-xl border border-[var(--line)] bg-white px-5 py-3 text-sm font-semibold text-[var(--navy)]"
          >
            Back to Dashboard
          </Link>
        </div>

        <section className="mb-6 rounded-2xl border border-[var(--line)] bg-white p-6 shadow-sm">
          <p className="text-sm text-[var(--muted)]">
            Total Leads
          </p>

          <p className="mt-2 text-3xl font-bold text-[var(--navy)]">
            {totalLeads}
          </p>
        </section>

        <section className="overflow-hidden rounded-2xl border border-[var(--line)] bg-white shadow-sm">
          <div className="border-b border-[var(--line)] px-6 py-5">
            <h2 className="text-lg font-bold text-[var(--navy)]">
              Recent Leads
            </h2>

            <p className="mt-1 text-sm text-[var(--muted)]">
              Showing up to 25 most recent leads.
            </p>
          </div>

          {leads.length === 0 ? (
            <div className="px-6 py-12 text-center">
              <p className="text-lg font-semibold text-[var(--navy)]">
                No leads found
              </p>

              <p className="mt-2 text-sm text-[var(--muted)]">
                New business enquiries will appear here
                once lead creation is enabled.
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[850px] text-left text-sm">
                <thead className="bg-slate-50 text-slate-600">
                  <tr>
                    <th className="px-5 py-4">Lead Code</th>
                    <th className="px-5 py-4">Name</th>
                    <th className="px-5 py-4">Company</th>
                    <th className="px-5 py-4">Service</th>
                    <th className="px-5 py-4">Source</th>
                    <th className="px-5 py-4">Status</th>
                    <th className="px-5 py-4">Assigned To</th>
                    <th className="px-5 py-4">Created</th>
                  </tr>
                </thead>

                <tbody className="divide-y divide-slate-100">
                  {leads.map((lead) => (
                    <tr key={lead.id}>
                      <td className="px-5 py-4 font-semibold text-[var(--navy)]">
                        <Link
                          href={`/admin/leads/${encodeURIComponent(lead.leadCode)}`}
                          className="text-[var(--blue)] underline-offset-4 hover:underline"
                        >
                          {lead.leadCode}
                        </Link>
                      </td>

                      <td className="px-5 py-4">
                        {lead.name}
                      </td>

                      <td className="px-5 py-4">
                        {lead.companyName || "—"}
                      </td>

                      <td className="px-5 py-4">
                        {lead.service || "—"}
                      </td>

                      <td className="px-5 py-4">
                        {lead.source}
                      </td>

                      <td className="px-5 py-4">
                        {lead.status}
                      </td>

                      <td className="px-5 py-4">
                        {lead.assignedTo?.name || "Unassigned"}
                      </td>

                      <td className="px-5 py-4">
                        {lead.createdAt.toLocaleDateString(
                          "en-IN",
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </section>
      </div>
    </main>
    </CustomerAdminShell>
  );
}
