import Link from "next/link";
import { indiaTodayDateString, utcDateOnly } from "@/lib/crm/follow-up-date";
import { prisma } from "@/lib/prisma";
import { requireCrmAdmin } from "@/lib/crm/admin-access";
import CustomerAdminShell from "@/app/admin/CustomerAdminShell";

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 AdminFollowUpsPage({
  searchParams,
}: {
  searchParams: Promise<{ filter?: string; page?: string }>;
}) {
  await requireCrmAdmin();

  const params = await searchParams;

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

  // Follow-up dates are stored as UTC-midnight date-only values.
  // Compare them against India's current calendar date, not the
  // server's UTC calendar date.
  const today = utcDateOnly(indiaTodayDateString());

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

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

  const pageSize = 25;

  const activeWhere = {
    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: {
      id: true,
      leadCode: true,
      name: true,
      companyName: true,
      status: true,
      nextFollowUpAt: true,
      assignedTo: {
        select: {
          name: 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,
    },
  ];

  const cards = [
    {
      label: "Overdue",
      value: overdue,
      description: "Follow-up date has passed",
      filter: "overdue",
    },
    {
      label: "Due Today",
      value: dueToday,
      description: "Scheduled for today",
      filter: "today",
    },
    {
      label: "Upcoming",
      value: upcoming,
      description: "Scheduled after today",
      filter: "upcoming",
    },
    {
      label: "Unscheduled",
      value: unscheduled,
      description: "No follow-up date set",
      filter: "unscheduled",
    },
  ];

  return (
    <CustomerAdminShell>
      <main className="w-full min-w-0 space-y-7 px-4 py-6 sm:px-6 lg:px-8 lg:py-8">
        <header className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <p className="text-xs font-bold uppercase tracking-widest text-blue-700">
              Lead Management
            </p>
            <h1 className="mt-2 text-2xl font-extrabold text-slate-900 sm:text-3xl">
              Follow-up Dashboard
            </h1>
            <p className="mt-2 text-sm text-slate-600">
              Review pending follow-ups across all active leads.
            </p>
          </div>

          <Link
            href="/admin/leads"
            className="rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700"
          >
            View All Leads
          </Link>
        </header>

        <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
          {cards.map((card) => (
            <Link
              key={card.filter}
              href={`/admin/follow-ups?filter=${card.filter}`}
              className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm transition hover:border-blue-300 hover:shadow-md"
            >
              <p className="text-sm font-semibold text-slate-500">
                {card.label}
              </p>
              <p className="mt-3 text-3xl font-extrabold text-slate-900">
                {card.value}
              </p>
              <p className="mt-2 text-xs text-slate-500">
                {card.description}
              </p>
            </Link>
          ))}
        </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-xl font-bold text-slate-900">
              Follow-up Queue
            </h2>

            <nav
              aria-label="Follow-up filters"
              className="mt-5 flex flex-wrap gap-2"
            >
              {filters.map((item) => (
                <Link
                  key={item.key}
                  href={`/admin/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.
              Follow-up dates use the India calendar day.
            </p>
          </div>

          {leads.length === 0 ? (
            <p className="p-8 text-sm text-slate-600">
              No active leads found for this filter.
            </p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[780px] 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">Assigned To</th>
                    <th className="px-5 py-4">Next Follow-up</th>
                    <th className="px-5 py-4">Action</th>
                  </tr>
                </thead>

                <tbody className="divide-y divide-slate-100">
                  {leads.map((lead) => (
                    <tr key={lead.id} className="hover:bg-slate-50">
                      <td className="px-5 py-4">
                        <p className="font-semibold text-slate-900">
                          {lead.name}
                        </p>
                        <p className="mt-1 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">
                        {lead.assignedTo?.name || "Unassigned"}
                      </td>

                      <td className="px-5 py-4">
                        {lead.nextFollowUpAt
                          ? lead.nextFollowUpAt.toLocaleDateString(
                              "en-IN",
                              { timeZone: "UTC" },
                            )
                          : "Not scheduled"}
                      </td>

                      <td className="px-5 py-4">
                        <Link
                          href={`/admin/leads/${encodeURIComponent(lead.leadCode)}`}
                          className="font-semibold text-blue-700 hover:underline"
                        >
                          Open Lead
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          <nav
            aria-label="Follow-up pagination"
            className="flex flex-wrap items-center justify-between gap-3 border-t border-slate-200 px-5 py-4"
          >
            <p className="text-sm text-slate-600">
              Page {page} of {totalPages}
            </p>

            <div className="flex flex-wrap gap-2">
              {page > 1 ? (
                <Link
                  href={`/admin/follow-ups?filter=${filter}&page=${page - 1}`}
                  className="rounded-lg border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                >
                  Previous
                </Link>
              ) : (
                <span className="rounded-lg border border-slate-200 px-4 py-2 text-sm text-slate-400">
                  Previous
                </span>
              )}

              {page < totalPages ? (
                <Link
                  href={`/admin/follow-ups?filter=${filter}&page=${page + 1}`}
                  className="rounded-lg bg-blue-700 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-800"
                >
                  Next
                </Link>
              ) : (
                <span className="rounded-lg border border-slate-200 px-4 py-2 text-sm text-slate-400">
                  Next
                </span>
              )}
            </div>
          </nav>
        </section>
      </main>
    </CustomerAdminShell>
  );
}
