import { indiaTodayDateString } from "@/lib/crm/follow-up-date";
import type { Metadata } from "next";
import Link from "next/link";
import { cookies } from "next/headers";
import { notFound, 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 {
  addStaffLeadNote,
  updateStaffLeadFollowUp,
  updateStaffLeadStatus,
} from "./actions";

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

export const dynamic = "force-dynamic";

type PageProps = {
  params: Promise<{ leadCode: string }>;
};

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

export default async function StaffLeadDetailsPage({
  params,
}: PageProps) {
  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 { leadCode } = await params;

  if (!/^TTL-[A-F0-9]{20}$/.test(leadCode)) {
    notFound();
  }

  const lead = await prisma.lead.findFirst({
    where: {
      leadCode,
      assignedToId: auth.userId,
    },
    select: {
      id: true,
      leadCode: true,
      name: true,
      companyName: true,
      email: true,
      phone: true,
      service: true,
      message: true,
      source: true,
      status: true,
      nextFollowUpAt: true,
      createdAt: true,
    },
  });

  if (!lead) {
    notFound();
  }


  // STAFF_LEAD_ACTIVITY_STEP98
  // The Lead was already verified as assigned to this staff member.
  const activity = await prisma.auditLog.findMany({
    where: {
      module: "CRM",
      entityType: "Lead",
      entityId: lead.id,
      action: {
        in: [
          "LEAD_NOTE_ADDED",
          "LEAD_STATUS_UPDATED",
          "LEAD_FOLLOW_UP_UPDATED",
          "LEAD_ASSIGNED",
          "LEAD_CONVERTED",
        ],
      },
    },
    orderBy: [
      { createdAt: "desc" },
      { id: "desc" },
    ],
    take: 30,
    select: {
      id: true,
      action: true,
      createdAt: true,
      oldValues: true,
      newValues: true,
      user: {
        select: {
          name: true,
        },
      },
    },
  });

  function readAuditField(
    value: unknown,
    key: string,
  ): string | null {
    if (
      !value ||
      typeof value !== "object" ||
      Array.isArray(value)
    ) {
      return null;
    }

    const field = (value as Record<string, unknown>)[key];

    return typeof field === "string" ? field : null;
  }

  function formatActivityDate(date: Date): string {
    return new Intl.DateTimeFormat("en-IN", {
      timeZone: "Asia/Kolkata",
      dateStyle: "medium",
      timeStyle: "short",
    }).format(date);
  }

  function formatAuditFollowUp(value: string | null): string {
    if (!value) return "Not scheduled";

    const parsed = new Date(value);

    if (!Number.isFinite(parsed.getTime())) return "Updated";

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

  const canUpdateFollowUp =
    hasPermission(auth, "LEAD_UPDATE") &&
    !CLOSED_STATUSES.includes(lead.status);

  const details: Array<[string, string]> = [
    ["Lead Code", lead.leadCode],
    ["Name", lead.name],
    ["Company", lead.companyName ?? "—"],
    ["Email", lead.email ?? "—"],
    ["Phone", lead.phone ?? "—"],
    ["Service", lead.service ?? "—"],
    ["Source", lead.source],
    ["Status", lead.status],
    [
      "Next Follow-up",
      lead.nextFollowUpAt
        ? lead.nextFollowUpAt.toLocaleDateString("en-IN")
        : "Not scheduled",
    ],
    [
      "Created",
      lead.createdAt.toLocaleDateString("en-IN"),
    ],
  ];

  return (
    <main className="min-h-screen w-full min-w-0 bg-slate-50 px-4 py-7 text-slate-900 sm:px-6 lg:px-8">
      <div className="mx-auto w-full max-w-7xl space-y-6">
        <div className="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">
              Lead Details
            </h1>
          </div>

          <Link
            href="/staff/leads"
            className="rounded-xl border bg-white px-5 py-3 text-sm font-semibold"
          >
            Back to My Leads
          </Link>
        </div>

        <section className="rounded-2xl border bg-white p-7">
          <dl className="grid gap-5 sm:grid-cols-2 xl:grid-cols-3">
            {details.map(([label, value]) => (
              <div key={label}>
                <dt className="text-xs font-semibold uppercase text-slate-500">
                  {label}
                </dt>

                <dd className="mt-1 break-words text-sm text-slate-900">
                  {value}
                </dd>
              </div>
            ))}
          </dl>

          <div className="mt-6 border-t pt-5">
            <h2 className="font-semibold">Customer Requirement</h2>

            <p className="mt-2 whitespace-pre-wrap break-words text-sm text-slate-600">
              {lead.message || "No additional requirement."}
            </p>
          </div>
        </section>


        {/* STAFF_LEAD_ACTIVITY_STEP98 */}
        {canUpdateFollowUp && (
          <section className="rounded-2xl border bg-white p-7">
            <h2 className="text-lg font-bold">
              Add Follow-up Note
            </h2>

            <p className="mt-2 text-sm text-slate-600">
              Record the conversation or next action for this lead.
              Saving a note does not change its status or follow-up date.
            </p>

            <form action={addStaffLeadNote} className="mt-5 space-y-4">
              <input
                type="hidden"
                name="leadCode"
                value={lead.leadCode}
              />

              <label
                htmlFor="staff-lead-note"
                className="block text-sm font-semibold"
              >
                Note
              </label>

              <textarea
                id="staff-lead-note"
                name="note"
                required
                minLength={2}
                maxLength={2000}
                rows={4}
                placeholder="Enter conversation details or the next action..."
                className="w-full rounded-xl border border-slate-300 px-4 py-3 text-sm"
              />

              <button
                type="submit"
                className="rounded-xl bg-blue-700 px-5 py-3 text-sm font-semibold text-white"
              >
                Save Note
              </button>
            </form>
          </section>
        )}

        <section className="rounded-2xl border bg-white p-7">
          <h2 className="text-lg font-bold">
            Lead Activity History
          </h2>

          <p className="mt-2 text-sm text-slate-600">
            Latest 30 recorded notes and lead updates.
          </p>

          {activity.length === 0 ? (
            <p className="mt-5 text-sm text-slate-500">
              No recorded activity for this lead yet.
            </p>
          ) : (
            <div className="mt-5 divide-y divide-slate-100">
              {activity.map((entry) => {
                const note = readAuditField(
                  entry.newValues,
                  "note",
                );

                const newStatus = readAuditField(
                  entry.newValues,
                  "status",
                );

                const oldStatus = readAuditField(
                  entry.oldValues,
                  "status",
                );

                const newFollowUp = readAuditField(
                  entry.newValues,
                  "nextFollowUpAt",
                );

                const oldFollowUp = readAuditField(
                  entry.oldValues,
                  "nextFollowUpAt",
                );

                const title =
                  entry.action === "LEAD_NOTE_ADDED"
                    ? "Note Added"
                    : entry.action === "LEAD_STATUS_UPDATED"
                      ? "Status Updated"
                      : entry.action === "LEAD_FOLLOW_UP_UPDATED"
                        ? "Follow-up Updated"
                        : entry.action === "LEAD_ASSIGNED"
                          ? "Lead Assigned"
                          : entry.action === "LEAD_CONVERTED"
                            ? "Lead Converted"
                            : "Lead Activity";

                return (
                  <article key={entry.id} className="py-4">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <h3 className="text-sm font-bold text-slate-900">
                        {title}
                      </h3>

                      <time className="text-xs text-slate-500">
                        {formatActivityDate(entry.createdAt)}
                      </time>
                    </div>

                    <p className="mt-1 text-xs text-slate-500">
                      By {entry.user?.name ?? "System"}
                    </p>

                    {note && (
                      <p className="mt-3 whitespace-pre-wrap break-words text-sm text-slate-700">
                        {note}
                      </p>
                    )}

                    {entry.action === "LEAD_STATUS_UPDATED" &&
                      newStatus && (
                        <p className="mt-2 text-sm text-slate-700">
                          {oldStatus
                            ? `${oldStatus} → ${newStatus}`
                            : newStatus}
                        </p>
                      )}

                    {entry.action === "LEAD_FOLLOW_UP_UPDATED" &&
                      newFollowUp && (
                        <p className="mt-2 text-sm text-slate-700">
                          {formatAuditFollowUp(oldFollowUp)}
                          {" → "}
                          {formatAuditFollowUp(newFollowUp)}
                        </p>
                      )}
                  </article>
                );
              })}
            </div>
          )}
        </section>

        {/* STAFF_LEAD_STATUS_UPDATE_STEP78 */}
        {canUpdateFollowUp && (
          <section className="rounded-2xl border bg-white p-7">
            <h2 className="text-lg font-bold">
              Update Lead Progress
            </h2>
            <p className="mt-2 text-sm text-slate-600">
              Update the progress of your assigned lead. Customer
              conversion and lead reassignment are managed by Admin.
            </p>
            <form
              action={updateStaffLeadStatus}
              className="mt-5 flex flex-wrap items-end gap-4"
            >
              <input
                type="hidden"
                name="leadCode"
                value={lead.leadCode}
              />
              <label className="block text-sm font-semibold">
                Lead Status
                <select
                  name="status"
                  required
                  defaultValue={lead.status}
                  className="mt-2 block rounded-xl border bg-white px-4 py-3"
                >
                  <option value="" disabled>Select status</option>
                  <option value="CONTACTED">Contacted</option>
                  <option value="QUALIFIED">Qualified</option>
                  <option value="REQUIREMENT_RECEIVED">
                    Requirement Received
                  </option>
                  <option value="QUOTATION_SENT">Quotation Sent</option>
                  <option value="NEGOTIATION">Negotiation</option>
                </select>
              </label>
              <button
                type="submit"
                className="rounded-xl bg-blue-700 px-5 py-3 text-sm font-semibold text-white"
              >
                Save Status
              </button>
            </form>
          </section>
        )}

        {canUpdateFollowUp && (
          <section className="rounded-2xl border bg-white p-7">
            <h2 className="text-lg font-bold">
              Schedule Next Follow-up
            </h2>

            <form
              action={updateStaffLeadFollowUp}
              className="mt-5 flex flex-wrap items-end gap-4"
            >
              <input
                type="hidden"
                name="leadCode"
                value={lead.leadCode}
              />

              <label className="block text-sm font-semibold">
                Follow-up Date
                <input
                  type="date"
                  name="nextFollowUpAt"
                  required
                  min={indiaTodayDateString()}
                  className="mt-2 block rounded-xl border px-4 py-3"
                />
              </label>

              <button
                type="submit"
                className="rounded-xl bg-blue-700 px-5 py-3 text-sm font-semibold text-white"
              >
                Save Follow-up
              </button>
            </form>
          </section>
        )}
      </div>
    </main>
  );
}
