import Link from "next/link";

import { requireCrmAdmin } from "@/lib/crm/admin-access";
import { prisma } from "@/lib/prisma";

import {
  createMilestone,
  updateMilestone,
} from "./actions";

const STATUSES = [
  "PENDING",
  "IN_PROGRESS",
  "CLIENT_REVIEW",
  "COMPLETED",
  "ON_HOLD",
] as const;

function dateInputValue(value: Date | null) {
  if (!value) return "";

  return new Intl.DateTimeFormat("en-CA", {
    timeZone: "Asia/Kolkata",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(value);
}

function displayDate(value: Date | null) {
  if (!value) return "—";

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

export default async function MilestonesPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  await requireCrmAdmin();

  const params = await searchParams;

  const [projects, milestones] = await Promise.all([
    prisma.project.findMany({
      where: {
        status: {
          notIn: ["CANCELLED", "ARCHIVED"],
        },
      },
      orderBy: [
        { updatedAt: "desc" },
        { name: "asc" },
      ],
      select: {
        id: true,
        projectCode: true,
        name: true,
        status: true,
      },
      take: 300,
    }),

    prisma.milestone.findMany({
      orderBy: [
        { project: { name: "asc" } },
        { sequence: "asc" },
        { createdAt: "asc" },
      ],
      select: {
        id: true,
        milestoneCode: true,
        title: true,
        description: true,
        status: true,
        sequence: true,
        startDate: true,
        dueDate: true,
        completedAt: true,
        createdAt: true,
        project: {
          select: {
            projectCode: true,
            name: true,
            status: true,
          },
        },
        _count: {
          select: {
            tasks: true,
          },
        },
      },
      take: 500,
    }),
  ]);

  const error =
    typeof params.error === "string"
      ? params.error
      : null;

  const created =
    typeof params.created === "string"
      ? params.created
      : null;

  const updated =
    typeof params.updated === "string"
      ? params.updated
      : null;

  const activeCount = milestones.filter(
    (item) =>
      item.status === "IN_PROGRESS" ||
      item.status === "CLIENT_REVIEW",
  ).length;

  const completedCount = milestones.filter(
    (item) => item.status === "COMPLETED",
  ).length;

  const overdueCount = milestones.filter(
    (item) =>
      item.dueDate &&
      item.dueDate.getTime() < Date.now() &&
      item.status !== "COMPLETED",
  ).length;

  return (
    <main className="space-y-6">
      <section>
        <p className="text-sm font-bold uppercase tracking-[0.2em] text-blue-600">
          Project Delivery
        </p>
        <h1 className="mt-2 text-3xl font-black text-slate-950">
          Milestones
        </h1>
        <p className="mt-2 max-w-3xl text-sm text-slate-600">
          Plan delivery stages, track dates and move project
          milestones through execution, client review and completion.
        </p>
      </section>

      {created && (
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm font-bold text-emerald-800">
          Milestone {created} created successfully.
        </div>
      )}

      {updated && (
        <div className="rounded-2xl border border-blue-200 bg-blue-50 p-4 text-sm font-bold text-blue-800">
          Milestone {updated} updated successfully.
        </div>
      )}

      {error && (
        <div className="rounded-2xl border border-rose-200 bg-rose-50 p-4 text-sm font-bold text-rose-800">
          Milestone operation could not be completed: {error}.
        </div>
      )}

      <section className="grid gap-4 md:grid-cols-4">
        {[
          ["Total", milestones.length],
          ["Active / Review", activeCount],
          ["Completed", completedCount],
          ["Overdue", overdueCount],
        ].map(([label, value]) => (
          <div
            key={String(label)}
            className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm"
          >
            <p className="text-xs font-black uppercase tracking-wider text-slate-500">
              {label}
            </p>
            <p className="mt-2 text-3xl font-black text-slate-950">
              {value}
            </p>
          </div>
        ))}
      </section>

      <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
        <h2 className="text-xl font-black text-slate-950">
          Add Milestone
        </h2>

        <form
          action={createMilestone}
          className="mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-3"
        >
          <label className="space-y-2">
            <span className="text-sm font-bold text-slate-700">
              Project
            </span>
            <select
              name="projectId"
              required
              className="w-full rounded-xl border border-slate-300 px-3 py-3"
            >
              <option value="">Select project</option>
              {projects.map((project) => (
                <option
                  key={project.id}
                  value={project.id}
                >
                  {project.projectCode} · {project.name}
                </option>
              ))}
            </select>
          </label>

          <label className="space-y-2">
            <span className="text-sm font-bold text-slate-700">
              Title
            </span>
            <input
              name="title"
              required
              maxLength={191}
              className="w-full rounded-xl border border-slate-300 px-3 py-3"
              placeholder="Development Phase"
            />
          </label>

          <label className="space-y-2">
            <span className="text-sm font-bold text-slate-700">
              Sequence
            </span>
            <input
              name="sequence"
              type="number"
              min="0"
              max="999999"
              defaultValue="0"
              className="w-full rounded-xl border border-slate-300 px-3 py-3"
            />
          </label>

          <label className="space-y-2">
            <span className="text-sm font-bold text-slate-700">
              Start Date
            </span>
            <input
              name="startDate"
              type="date"
              className="w-full rounded-xl border border-slate-300 px-3 py-3"
            />
          </label>

          <label className="space-y-2">
            <span className="text-sm font-bold text-slate-700">
              Due Date
            </span>
            <input
              name="dueDate"
              type="date"
              className="w-full rounded-xl border border-slate-300 px-3 py-3"
            />
          </label>

          <label className="space-y-2 md:col-span-2 xl:col-span-3">
            <span className="text-sm font-bold text-slate-700">
              Description
            </span>
            <textarea
              name="description"
              rows={3}
              maxLength={10000}
              className="w-full rounded-xl border border-slate-300 px-3 py-3"
              placeholder="Scope and delivery objective..."
            />
          </label>

          <div className="md:col-span-2 xl:col-span-3">
            <button
              type="submit"
              className="rounded-xl bg-blue-600 px-5 py-3 font-extrabold text-white transition hover:bg-blue-700"
            >
              Create Milestone
            </button>
          </div>
        </form>
      </section>

      <section className="space-y-4">
        {milestones.length === 0 ? (
          <div className="rounded-3xl border border-dashed border-slate-300 bg-white p-8 text-center text-slate-500">
            No milestones created yet.
          </div>
        ) : (
          milestones.map((item) => (
            <article
              key={item.id}
              className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm"
            >
              <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
                <div>
                  <p className="text-xs font-black uppercase tracking-wider text-blue-600">
                    {item.milestoneCode}
                  </p>
                  <h2 className="mt-1 text-xl font-black text-slate-950">
                    {item.title}
                  </h2>
                  <p className="mt-1 text-sm text-slate-600">
                    <Link
                      href={`/admin/projects/${item.project.projectCode}`}
                      className="font-bold text-blue-700 hover:underline"
                    >
                      {item.project.projectCode} · {item.project.name}
                    </Link>
                  </p>

                  {item.description && (
                    <p className="mt-3 max-w-3xl whitespace-pre-wrap text-sm text-slate-600">
                      {item.description}
                    </p>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-2 text-xs font-bold text-slate-600 sm:grid-cols-4">
                  <span className="rounded-xl bg-slate-100 px-3 py-2">
                    Seq {item.sequence}
                  </span>
                  <span className="rounded-xl bg-slate-100 px-3 py-2">
                    {item._count.tasks} Tasks
                  </span>
                  <span className="rounded-xl bg-slate-100 px-3 py-2">
                    Due {displayDate(item.dueDate)}
                  </span>
                  <span className="rounded-xl bg-slate-100 px-3 py-2">
                    {item.status.replaceAll("_", " ")}
                  </span>
                </div>
              </div>

              <form
                action={updateMilestone}
                className="mt-5 grid gap-3 border-t border-slate-100 pt-5 md:grid-cols-2 xl:grid-cols-5"
              >
                <input
                  type="hidden"
                  name="milestoneCode"
                  value={item.milestoneCode}
                />

                <label className="space-y-1">
                  <span className="text-xs font-bold text-slate-600">
                    Status
                  </span>
                  <select
                    name="status"
                    defaultValue={item.status}
                    className="w-full rounded-xl border border-slate-300 px-3 py-2.5"
                  >
                    {/* MILESTONE_UI_LIFECYCLE_STEP172 */}
                    {(
                      {
                        PENDING: [
                          "PENDING",
                          "IN_PROGRESS",
                          "ON_HOLD",
                        ],
                        IN_PROGRESS: [
                          "IN_PROGRESS",
                          "CLIENT_REVIEW",
                          "ON_HOLD",
                        ],
                        CLIENT_REVIEW: [
                          "CLIENT_REVIEW",
                          "IN_PROGRESS",
                          "COMPLETED",
                          "ON_HOLD",
                        ],
                        COMPLETED: ["COMPLETED"],
                        ON_HOLD: [
                          "ON_HOLD",
                          "PENDING",
                          "IN_PROGRESS",
                        ],
                      } as Record<
                        typeof item.status,
                        readonly typeof item.status[]
                      >
                    )[item.status].map((status) => (
                      <option
                        key={status}
                        value={status}
                      >
                        {status.replaceAll("_", " ")}
                      </option>
                    ))}
                  </select>
                </label>

                <label className="space-y-1">
                  <span className="text-xs font-bold text-slate-600">
                    Sequence
                  </span>
                  <input
                    name="sequence"
                    type="number"
                    min="0"
                    max="999999"
                    defaultValue={item.sequence}
                    className="w-full rounded-xl border border-slate-300 px-3 py-2.5"
                  />
                </label>

                <label className="space-y-1">
                  <span className="text-xs font-bold text-slate-600">
                    Start Date
                  </span>
                  <input
                    name="startDate"
                    type="date"
                    defaultValue={dateInputValue(item.startDate)}
                    className="w-full rounded-xl border border-slate-300 px-3 py-2.5"
                  />
                </label>

                <label className="space-y-1">
                  <span className="text-xs font-bold text-slate-600">
                    Due Date
                  </span>
                  <input
                    name="dueDate"
                    type="date"
                    defaultValue={dateInputValue(item.dueDate)}
                    className="w-full rounded-xl border border-slate-300 px-3 py-2.5"
                  />
                </label>

                <div className="flex items-end">
                  <button
                    type="submit"
                    className="w-full rounded-xl bg-slate-950 px-4 py-2.5 font-extrabold text-white transition hover:bg-slate-800"
                  >
                    Save Milestone
                  </button>
                </div>
              </form>

              {item.completedAt && (
                <p className="mt-3 text-xs font-bold text-emerald-700">
                  Completed: {displayDate(item.completedAt)}
                </p>
              )}
            </article>
          ))
        )}
      </section>
    </main>
  );
}
