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

export const metadata: Metadata = {
  title: "My Follow-ups | Teja Technology CRM",
  robots: {
    index: false,
    follow: false,
  },
};

export const dynamic = "force-dynamic";

type Filter =
  | "all"
  | "overdue"
  | "today"
  | "upcoming"
  | "unscheduled";

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

export default async function StaffFollowUpsPage({
  searchParams,
}: {
  searchParams: Promise<{ filter?: string; page?: string }>;
}) {
  // STEP95_STAFF_FOLLOWUPS: Authentication and access control.
  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/follow-ups");
  }

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

  const params = await searchParams;

  const filter: Filter =
    params.filter === "overdue" ||
    params.filter === "today" ||
    params.filter === "upcoming" ||
    params.filter === "unscheduled"
      ? params.filter
      : "all";

  const requestedPage =
    typeof params.page === "string" &&
    /^[1-9][0-9]{0,5}$/.test(params.page)
      ? Number(params.page)
      : 1;

  const pageSize = 25;

  // CRM follow-up dates are stored at UTC midnight.
  // Compare against the India calendar date.
  const today = utcDateOnly(indiaTodayDateString());
  const tomorrow = new Date(
    today.getTime() + 24 * 60 * 60 * 1000,
  );

  // Every query is restricted to this authenticated staff member.
  const activeWhere = {
    assignedToId: auth.userId,
    status: {
      notIn: [...CLOSED_STATUSES],
    },
  };

  const [overdue, dueToday, upcoming, unscheduled] =
    await Promise.all([
      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,
        },
      }),
    ]);

  const dateWhere =
    filter === "overdue"
      ? { nextFollowUpAt: { lt: today } }
      : filter === "today"
        ? {
            nextFollowUpAt: {
              gte: today,
              lt: tomorrow,
            },
          }
        : filter === "upcoming"
          ? { nextFollowUpAt: { gte: tomorrow } }
          : filter === "unscheduled"
            ? { nextFollowUpAt: null }
            : {};

  const filteredWhere = {
    ...activeWhere,
    ...dateWhere,
  };

  const totalFiltered = await prisma.lead.count({
    where: filteredWhere,
  });

  const totalPages = Math.max(
    1,
    Math.ceil(totalFiltered / pageSize),
  );

  const page = Math.min(requestedPage, totalPages);

  const leads = await prisma.lead.findMany({
    where: filteredWhere,
    orderBy: [
      { nextFollowUpAt: "asc" },
      { createdAt: "desc" },
      { id: "asc" },
    ],
    skip: (page - 1) * pageSize,
    take: pageSize,
    select: {
      leadCode: true,
      name: true,
      companyName: true,
      status: true,
      nextFollowUpAt: true,
    },
  });

  const filters: {
    key: Filter;
    label: string;
    count?: number;
  }[] = [
    { key: "all", label: "All Active" },
    { key: "overdue", label: "Overdue", count: overdue },
    { key: "today", label: "Today", count: dueToday },
    { key: "upcoming", label: "Upcoming", count: upcoming },
    {
      key: "unscheduled",
      label: "Unscheduled",
      count: unscheduled,
    },
  ];

  function formatFollowUp(date: Date | null): string {
    if (!date) return "Not scheduled";

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

  function pageHref(targetPage: number): string {
    return `/staff/follow-ups?filter=${filter}&page=${targetPage}`;
  }

  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-6">
        <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">
              My Follow-ups
            </h1>
            <p className="mt-2 text-sm text-slate-600">
              Track follow-ups for leads assigned to your account.
            </p>
          </div>

          <Link
            href="/staff/leads"
            className="rounded-xl border border-slate-300 bg-white px-4 py-3 text-sm font-semibold text-slate-700"
          >
            My Assigned Leads
          </Link>
        </header>

        <section
          aria-label="My follow-up statistics"
          className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4"
        >
          {[
            { label: "Overdue", value: overdue },
            { label: "Due Today", value: dueToday },
            { label: "Upcoming", value: upcoming },
            { label: "Unscheduled", value: unscheduled },
          ].map((item) => (
            <div
              key={item.label}
              className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"
            >
              <p className="text-sm font-semibold text-slate-600">
                {item.label}
              </p>
              <p className="mt-3 text-3xl font-extrabold">
                {item.value}
              </p>
            </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 sm:p-6">
            <h2 className="text-lg font-bold">
              Follow-up Queue
            </h2>

            <nav
              aria-label="My follow-up filters"
              className="mt-4 flex flex-wrap gap-2"
            >
              {filters.map((item) => (
                <Link
                  key={item.key}
                  href={`/staff/follow-ups?filter=${item.key}`}
                  aria-current={
                    filter === item.key ? "page" : undefined
                  }
                  className={
                    filter === item.key
                      ? "rounded-lg bg-blue-700 px-4 py-2 text-sm font-bold text-white"
                      : "rounded-lg bg-slate-100 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-200"
                  }
                >
                  {item.label}
                  {item.count === undefined
                    ? ""
                    : ` (${item.count})`}
                </Link>
              ))}
            </nav>

            <p className="mt-4 text-xs text-slate-500">
              Showing {leads.length} of {totalFiltered} active leads.
              Dates use the India calendar day.
            </p>
          </div>

          {leads.length === 0 ? (
            <p className="p-8 text-sm text-slate-600">
              No assigned active leads found for this filter.
            </p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[700px] text-left text-sm">
                <thead className="bg-slate-50 text-slate-600">
                  <tr>
                    <th className="px-5 py-4">Lead</th>
                    <th className="px-5 py-4">Company</th>
                    <th className="px-5 py-4">Status</th>
                    <th className="px-5 py-4">Follow-up Date</th>
                    <th className="px-5 py-4">Action</th>
                  </tr>
                </thead>
                <tbody>
                  {leads.map((lead) => (
                    <tr
                      key={lead.leadCode}
                      className="border-t border-slate-100"
                    >
                      <td className="px-5 py-4">
                        <p className="font-semibold text-slate-900">
                          {lead.name}
                        </p>
                        <p className="mt-1 break-all text-xs text-slate-500">
                          {lead.leadCode}
                        </p>
                      </td>
                      <td className="px-5 py-4">
                        {lead.companyName || "—"}
                      </td>
                      <td className="px-5 py-4">
                        {lead.status}
                      </td>
                      <td className="px-5 py-4">
                        {formatFollowUp(lead.nextFollowUpAt)}
                      </td>
                      <td className="px-5 py-4">
                        <Link
                          href={`/staff/leads/${encodeURIComponent(lead.leadCode)}`}
                          className="font-bold text-blue-700 hover:underline"
                        >
                          Open Lead
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {totalPages > 1 && (
            <div className="flex flex-wrap items-center justify-between gap-3 border-t border-slate-200 p-5">
              <span className="text-sm text-slate-600">
                Page {page} of {totalPages}
              </span>

              <div className="flex gap-3">
                {page > 1 && (
                  <Link
                    href={pageHref(page - 1)}
                    className="rounded-lg border border-slate-300 px-4 py-2 text-sm font-semibold"
                  >
                    Previous
                  </Link>
                )}

                {page < totalPages && (
                  <Link
                    href={pageHref(page + 1)}
                    className="rounded-lg border border-slate-300 px-4 py-2 text-sm font-semibold"
                  >
                    Next
                  </Link>
                )}
              </div>
            </div>
          )}
        </section>
      </div>
    </main>
  );
}
