import type { Metadata } from "next";
import Link from "next/link";
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: "Assigned Leads | Teja Technology CRM",
  robots: {
    index: false,
    follow: false,
  },
};

export const dynamic = "force-dynamic";

export default async function StaffLeadsPage() {
  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 auth = await loadAuthorizationForUser(session.userId);

  if (
    !auth ||
    auth.status !== "ACTIVE" ||
    auth.roles.length === 0
  ) {
    redirect("/admin/login");
  }

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

  if (auth.roles.includes("SUPER_ADMIN")) {
    redirect("/admin/leads");
  }

  if (!hasPermission(auth, "LEAD_VIEW")) {
    redirect("/staff");
  }

  const leads = await prisma.lead.findMany({
    where: {
      assignedToId: auth.userId,
    },
    orderBy: [
      { createdAt: "desc" },
      { id: "desc" },
    ],
    take: 50,
    select: {
      leadCode: true,
      name: true,
      companyName: true,
      service: true,
      source: true,
      status: true,
      createdAt: true,
    },
  });

  return (
    <main className="min-h-screen bg-slate-50 px-5 py-12 text-slate-900">
      <div className="mx-auto max-w-6xl">
        <div className="mb-8 flex flex-wrap items-center justify-between gap-4">
          <div>
            <p className="text-sm font-semibold text-blue-700">
              Teja Technology CRM
            </p>

            <h1 className="mt-2 text-3xl font-bold">
              My Assigned Leads
            </h1>

            <p className="mt-2 text-sm text-slate-600">
              Showing up to 50 leads assigned to your account.
            </p>
          </div>

          <Link
            href="/staff"
            className="rounded-xl border bg-white px-5 py-3 text-sm font-semibold"
          >
            Staff Workspace
          </Link>
        </div>

        <section className="overflow-x-auto rounded-2xl border bg-white">
          <table className="w-full min-w-[750px] text-left text-sm">
            <thead className="bg-slate-100">
              <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">Created</th>
              </tr>
            </thead>

            <tbody>
              {leads.map((lead) => (
                <tr key={lead.leadCode} className="border-t">
                  <td className="px-5 py-4 font-semibold">
                    <Link
                      href={`/staff/leads/${encodeURIComponent(lead.leadCode)}`}
                      className="text-blue-700 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.createdAt.toLocaleDateString("en-IN")}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {leads.length === 0 && (
            <p className="px-5 py-10 text-center text-sm text-slate-500">
              No leads are currently assigned to your account.
            </p>
          )}
        </section>

        <p className="mt-5 text-sm text-slate-500">
          Lead assignment and customer conversion are managed by Admin.
          Open an assigned lead to update its progress or follow-up date.
        </p>
      </div>
    </main>
  );
}
