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";
import {
  indiaTodayDateString,
  utcDateOnly,
} from "@/lib/crm/follow-up-date";

export const dynamic = "force-dynamic";

export default async function StaffWorkspacePage() {
  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");
  }


  // STAFF_DASHBOARD_STEP91
  // All lead queries are restricted to the authenticated staff member.
  const canViewLeads = hasPermission(auth, "LEAD_VIEW");

  const todayString = indiaTodayDateString();
  const today = utcDateOnly(todayString);
  const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);

  const closedStatuses = [
    "CONVERTED",
    "DUPLICATE",
    "LOST",
    "CLOSED",
    "NOT_INTERESTED",
  ] as const;

  const assignedWhere = {
    assignedToId: auth.userId,
  };

  const activeWhere = {
    ...assignedWhere,
    status: {
      notIn: [...closedStatuses],
    },
  };

  const [
    totalAssigned,
    activeAssigned,
    overdue,
    dueToday,
    upcoming,
    unscheduled,
    recentLeads,
    nextFollowUps,
  ] = canViewLeads
    ? await Promise.all([
        prisma.lead.count({
          where: assignedWhere,
        }),
        prisma.lead.count({
          where: activeWhere,
        }),
        prisma.lead.count({
          where: {
            ...activeWhere,
            nextFollowUpAt: { lt: today },
          },
        }),
        prisma.lead.count({
          where: {
            ...activeWhere,
            nextFollowUpAt: {
              gte: today,
              lt: tomorrow,
            },
          },
        }),
        prisma.lead.count({
          where: {
            ...activeWhere,
            nextFollowUpAt: { gte: tomorrow },
          },
        }),
        prisma.lead.count({
          where: {
            ...activeWhere,
            nextFollowUpAt: null,
          },
        }),
        prisma.lead.findMany({
          where: assignedWhere,
          orderBy: [
            { createdAt: "desc" },
            { id: "desc" },
          ],
          take: 5,
          select: {
            leadCode: true,
            name: true,
            companyName: true,
            status: true,
          },
        }),
        prisma.lead.findMany({
          where: {
            ...activeWhere,
            nextFollowUpAt: { not: null },
          },
          orderBy: [
            { nextFollowUpAt: "asc" },
            { id: "asc" },
          ],
          take: 5,
          select: {
            leadCode: true,
            name: true,
            status: true,
            nextFollowUpAt: true,
          },
        }),
      ])
    : [0, 0, 0, 0, 0, 0, [], []];

  const metrics = [
    {
      label: "Total Assigned Leads",
      value: totalAssigned,
      detail: "All leads assigned to you",
    },
    {
      label: "Active Leads",
      value: activeAssigned,
      detail: "Leads still in progress",
    },
    {
      label: "Overdue Follow-ups",
      value: overdue,
      detail: "Follow-up date has passed",
    },
    {
      label: "Due Today",
      value: dueToday,
      detail: "Scheduled for today",
    },
    {
      label: "Upcoming Follow-ups",
      value: upcoming,
      detail: "Scheduled after today",
    },
    {
      label: "Unscheduled",
      value: unscheduled,
      detail: "Active leads without a follow-up date",
    },
  ];

  function formatFollowUp(date: Date | null) {
    if (!date) return "—";

    return new Intl.DateTimeFormat("en-IN", {
      timeZone: "UTC",
      day: "2-digit",
      month: "short",
      year: "numeric",
    }).format(date);
  }

  return (
    <main className="w-full min-w-0 px-4 py-7 text-slate-900 sm:px-6 lg:px-8">
      <div className="mx-auto max-w-7xl space-y-7">
        <header className="flex flex-wrap items-center justify-between gap-4">
          <div>
            <p className="text-xs font-bold uppercase tracking-widest text-blue-700">
              Teja Technology CRM
            </p>
            <h1 className="mt-2 text-3xl font-extrabold">
              Staff Dashboard
            </h1>
            <p className="mt-2 text-sm text-slate-600">
              Welcome, {auth.name}. Manage your assigned leads and follow-ups.
            </p>
            <p className="mt-1 text-xs text-slate-500">
              User Code: {auth.userCode} · Today: {formatFollowUp(today)}
            </p>
          </div>

          {canViewLeads && (
            <Link
              href="/staff/leads"
              className="rounded-xl bg-blue-700 px-5 py-3 text-sm font-bold text-white hover:bg-blue-800"
            >
              View My Assigned Leads
            </Link>
          )}
        </header>

        {!canViewLeads ? (
          <section className="rounded-2xl border border-slate-200 bg-white p-7">
            <h2 className="text-lg font-bold">Workspace Access</h2>
            <p className="mt-2 text-sm text-slate-600">
              Lead dashboard access is not enabled for your account.
              Contact your CRM administrator if you require access.
            </p>
          </section>
        ) : (
          <>
            <section
              aria-label="My lead statistics"
              className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3"
            >
              {metrics.map((metric) => (
                <div
                  key={metric.label}
                  className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"
                >
                  <p className="text-sm font-semibold text-slate-600">
                    {metric.label}
                  </p>
                  <p className="mt-3 text-3xl font-extrabold text-slate-900">
                    {metric.value}
                  </p>
                  <p className="mt-2 text-xs text-slate-500">
                    {metric.detail}
                  </p>
                </div>
              ))}
            </section>

            <div className="grid gap-6 xl:grid-cols-2">
              <section className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
                <div className="border-b border-slate-200 p-5">
                  <h2 className="text-lg font-bold">
                    Next Follow-ups
                  </h2>
                  <p className="mt-1 text-sm text-slate-500">
                    Your next five scheduled active leads, earliest first.
                  </p>
                </div>

                {nextFollowUps.length === 0 ? (
                  <p className="p-5 text-sm text-slate-500">
                    No scheduled follow-ups for your active leads.
                  </p>
                ) : (
                  <div className="divide-y divide-slate-100">
                    {nextFollowUps.map((lead) => (
                      <Link
                        key={lead.leadCode}
                        href={`/staff/leads/${encodeURIComponent(lead.leadCode)}`}
                        className="flex flex-wrap items-center justify-between gap-3 p-5 hover:bg-slate-50"
                      >
                        <div className="min-w-0">
                          <p className="break-all text-sm font-bold text-blue-700">
                            {lead.leadCode}
                          </p>
                          <p className="mt-1 text-sm text-slate-700">
                            {lead.name} · {lead.status}
                          </p>
                        </div>
                        <span className="text-sm font-semibold text-slate-700">
                          {formatFollowUp(lead.nextFollowUpAt)}
                        </span>
                      </Link>
                    ))}
                  </div>
                )}
              </section>

              <section className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
                <div className="border-b border-slate-200 p-5">
                  <h2 className="text-lg font-bold">
                    Recently Assigned Leads
                  </h2>
                  <p className="mt-1 text-sm text-slate-500">
                    Your five most recently created assigned leads.
                  </p>
                </div>

                {recentLeads.length === 0 ? (
                  <p className="p-5 text-sm text-slate-500">
                    No leads are currently assigned to your account.
                  </p>
                ) : (
                  <div className="divide-y divide-slate-100">
                    {recentLeads.map((lead) => (
                      <Link
                        key={lead.leadCode}
                        href={`/staff/leads/${encodeURIComponent(lead.leadCode)}`}
                        className="block p-5 hover:bg-slate-50"
                      >
                        <p className="break-all text-sm font-bold text-blue-700">
                          {lead.leadCode}
                        </p>
                        <p className="mt-1 text-sm text-slate-700">
                          {lead.name}
                          {lead.companyName
                            ? ` · ${lead.companyName}`
                            : ""}
                        </p>
                        <p className="mt-1 text-xs font-semibold text-slate-500">
                          {lead.status}
                        </p>
                      </Link>
                    ))}
                  </div>
                )}
              </section>
            </div>
          </>
        )}

        <footer className="rounded-2xl border border-slate-200 bg-white px-5 py-4 text-sm text-slate-600">
          Signed in as {auth.name} · {auth.roles.join(", ")}
          <Link
            href="/admin/change-password"
            className="ml-3 font-semibold text-blue-700 hover:underline"
          >
            Change Password
          </Link>
        </footer>
      </div>
    </main>
  );
}
