import { prisma } from "@/lib/prisma";
import { requireCrmAdmin } from "@/lib/crm/admin-access";
import CustomerAdminShell from "../CustomerAdminShell";
import { createTask, updateTask } from "./actions";

export const dynamic = "force-dynamic";

const statuses = [
  "TODO",
  "IN_PROGRESS",
  "CODE_REVIEW",
  "QA_TESTING",
  "CLIENT_REVIEW",
  "COMPLETED",
  "BLOCKED",
  "CANCELLED",
];

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

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

export default async function TasksPage() {
  await requireCrmAdmin();

  const [tasks, projects, staff, milestones] = await Promise.all([
    prisma.task.findMany({
      orderBy: { createdAt: "desc" },
      take: 100,
      select: {
        taskCode: true,
        title: true,
        description: true,
        status: true,
        priority: true,
        estimatedHours: true,
        actualHours: true,
        dueDate: true,
        assigneeId: true,
        milestoneId: true,
        milestone: {
          select: {
            milestoneCode: true,
            title: true,
          },
        },
        assignee: {
          select: {
            name: true,
            userCode: true,
          },
        },
        project: {
          select: {
            id: true,
            name: true,
            projectCode: true,
          },
        },
      },
    }),

    prisma.project.findMany({
      orderBy: { createdAt: "desc" },
      take: 500,
      select: {
        id: true,
        name: true,
        projectCode: true,
      },
    }),

    prisma.user.findMany({
      where: {
        status: "ACTIVE",
        roles: {
          some: {
            role: {
              name: { not: "SUPER_ADMIN" },
            },
          },
        },
      },
      orderBy: {
        name: "asc",
      },
      take: 500,
      select: {
        id: true,
        name: true,
        userCode: true,
      },
    }),

    prisma.milestone.findMany({
      where: {
        project: {
          status: {
            notIn: ["CANCELLED", "ARCHIVED"],
          },
        },
      },
      orderBy: [
        { projectId: "asc" },
        { sequence: "asc" },
        { createdAt: "asc" },
      ],
      take: 500,
      select: {
        id: true,
        milestoneCode: true,
        title: true,
        sequence: true,
        projectId: true,
        project: {
          select: {
            name: true,
            projectCode: true,
          },
        },
      },
    }),
  ]);

  return (
    <CustomerAdminShell>
      <main className="mx-auto max-w-6xl space-y-8 px-5 py-8">
        <div>
          <h1 className="text-3xl font-bold">
            Task Management
          </h1>

          <p className="mt-2 text-sm text-slate-500">
            Create, assign and track project work.
          </p>
        </div>

        <section className="rounded-2xl border bg-white p-6">
          <h2 className="mb-4 text-xl font-bold">
            Create Task
          </h2>

          <form
            action={createTask}
            className="grid gap-4 md:grid-cols-2"
          >
            <select
              name="projectId"
              required
              defaultValue=""
              className="rounded-xl border p-3 md:col-span-2"
            >
              <option value="" disabled>
                Select Project
              </option>

              {projects.map((project) => (
                <option
                  key={project.id}
                  value={project.id}
                >
                  {project.name} — {project.projectCode}
                </option>
              ))}
            </select>

            {/* TASK_MILESTONE_UI_STEP168 */}
            <label className="grid gap-1 text-sm md:col-span-2">
              <span className="font-semibold">
                Milestone
              </span>

              <select
                name="milestoneId"
                defaultValue=""
                className="rounded-xl border p-3"
              >
                <option value="">
                  No Milestone
                </option>

                {milestones.map((milestone) => (
                  <option
                    key={milestone.id}
                    value={milestone.id}
                  >
                    {milestone.project.name} —{" "}
                    {milestone.milestoneCode} —{" "}
                    {milestone.title}
                  </option>
                ))}
              </select>

              <span className="text-xs text-slate-500">
                Select a milestone belonging to the selected project.
              </span>
            </label>

            <input
              name="title"
              required
              maxLength={191}
              placeholder="Task Title"
              className="rounded-xl border p-3 md:col-span-2"
            />

            <textarea
              name="description"
              maxLength={10000}
              rows={4}
              placeholder="Task Description"
              className="rounded-xl border p-3 md:col-span-2"
            />

            <select
              name="priority"
              defaultValue="NORMAL"
              className="rounded-xl border p-3"
            >
              <option value="LOW">Low Priority</option>
              <option value="NORMAL">Normal Priority</option>
              <option value="HIGH">High Priority</option>
              <option value="URGENT">Urgent Priority</option>
            </select>

            <select
              name="assigneeId"
              defaultValue=""
              className="rounded-xl border p-3"
            >
              <option value="">Unassigned</option>

              {staff.map((user) => (
                <option key={user.id} value={user.id}>
                  {user.name} — {user.userCode}
                </option>
              ))}
            </select>

            <label className="grid gap-1 text-sm">
              <span className="font-semibold">
                Due Date
              </span>

              <input
                name="dueDate"
                type="date"
                className="rounded-xl border p-3"
              />
            </label>

            <label className="grid gap-1 text-sm">
              <span className="font-semibold">
                Estimated Hours
              </span>

              <input
                name="estimatedHours"
                type="number"
                min="0"
                max="999999.99"
                step="0.25"
                className="rounded-xl border p-3"
                placeholder="Example: 8"
              />
            </label>

            <button
              type="submit"
              className="rounded-xl bg-blue-600 p-3 font-bold text-white md:col-span-2"
            >
              Create Task
            </button>
          </form>
        </section>

        <section className="space-y-4">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <h2 className="text-xl font-bold">Tasks</h2>

            <p className="text-sm text-slate-500">
              Showing latest {tasks.length} task
              {tasks.length === 1 ? "" : "s"}
            </p>
          </div>

          {tasks.length === 0 && (
            <p className="rounded-xl border bg-white p-5 text-sm">
              No tasks created yet.
            </p>
          )}

          {tasks.map((task) => (
            <article
              key={task.taskCode}
              className="rounded-2xl border bg-white p-5"
            >
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <h3 className="font-bold">
                    {task.title}
                  </h3>

                  <p className="mt-1 text-xs text-slate-500">
                    {task.taskCode} · {task.project.name} ·{" "}
                    {task.priority}
                  </p>
                </div>

                <span className="rounded-full border px-3 py-1 text-xs font-semibold">
                  {task.status}
                </span>
              </div>

              {task.description && (
                <p className="mt-3 whitespace-pre-wrap text-sm">
                  {task.description}
                </p>
              )}

              <div className="mt-4 grid gap-2 text-sm text-slate-600 md:grid-cols-4">
                <p>
                  <strong>Assignee:</strong>{" "}
                  {task.assignee
                    ? `${task.assignee.name} (${task.assignee.userCode})`
                    : "Unassigned"}
                </p>

                <p>
                  <strong>Milestone:</strong>{" "}
                  {task.milestone
                    ? `${task.milestone.milestoneCode} — ${task.milestone.title}`
                    : "Not linked"}
                </p>

                <p>
                  <strong>Due:</strong>{" "}
                  {task.dueDate
                    ? new Intl.DateTimeFormat("en-IN", {
                        timeZone: "Asia/Kolkata",
                        dateStyle: "medium",
                      }).format(task.dueDate)
                    : "Not set"}
                </p>

                <p>
                  <strong>Hours:</strong>{" "}
                  {task.actualHours?.toString() ?? "0"} /{" "}
                  {task.estimatedHours?.toString() ?? "—"}
                </p>
              </div>

              <form
                action={updateTask}
                className="mt-5 grid gap-3 rounded-xl bg-slate-50 p-4 md:grid-cols-2"
              >
                <input
                  type="hidden"
                  name="taskCode"
                  value={task.taskCode}
                />

                <label className="grid gap-1 text-sm">
                  <span className="font-semibold">
                    Status
                  </span>

                  <select
                    name="status"
                    defaultValue={task.status}
                    className="rounded-xl border bg-white p-2"
                  >
                    {/* ADMIN_TASK_UI_LIFECYCLE_STEP172 */}
                    {(
                      {
                        TODO: [
                          "TODO",
                          "IN_PROGRESS",
                          "BLOCKED",
                          "CANCELLED",
                        ],
                        IN_PROGRESS: [
                          "IN_PROGRESS",
                          "CODE_REVIEW",
                          "BLOCKED",
                          "CANCELLED",
                        ],
                        CODE_REVIEW: [
                          "CODE_REVIEW",
                          "IN_PROGRESS",
                          "QA_TESTING",
                          "BLOCKED",
                          "CANCELLED",
                        ],
                        QA_TESTING: [
                          "QA_TESTING",
                          "CODE_REVIEW",
                          "CLIENT_REVIEW",
                          "BLOCKED",
                          "CANCELLED",
                        ],
                        CLIENT_REVIEW: [
                          "CLIENT_REVIEW",
                          "QA_TESTING",
                          "COMPLETED",
                          "BLOCKED",
                          "CANCELLED",
                        ],
                        COMPLETED: ["COMPLETED"],
                        BLOCKED: [
                          "BLOCKED",
                          "TODO",
                          "IN_PROGRESS",
                          "CODE_REVIEW",
                          "QA_TESTING",
                          "CLIENT_REVIEW",
                          "CANCELLED",
                        ],
                        CANCELLED: ["CANCELLED"],
                      } as Record<
                        typeof task.status,
                        readonly typeof task.status[]
                      >
                    )[task.status].map((status) => (
                      <option key={status} value={status}>
                        {status.replaceAll("_", " ")}
                      </option>
                    ))}
                  </select>
                </label>

                <label className="grid gap-1 text-sm">
                  <span className="font-semibold">
                    Milestone
                  </span>

                  <select
                    name="milestoneId"
                    defaultValue={task.milestoneId ?? ""}
                    className="rounded-xl border bg-white p-2"
                  >
                    <option value="">
                      No Milestone
                    </option>

                    {milestones
                      .filter(
                        (milestone) =>
                          milestone.projectId === task.project.id,
                      )
                      .map((milestone) => (
                        <option
                          key={milestone.id}
                          value={milestone.id}
                        >
                          {milestone.milestoneCode} —{" "}
                          {milestone.title}
                        </option>
                      ))}
                  </select>
                </label>

                <label className="grid gap-1 text-sm">
                  <span className="font-semibold">
                    Assignee
                  </span>

                  <select
                    name="assigneeId"
                    defaultValue={task.assigneeId ?? ""}
                    className="rounded-xl border bg-white p-2"
                  >
                    <option value="">Unassigned</option>

                    {staff.map((user) => (
                      <option key={user.id} value={user.id}>
                        {user.name} — {user.userCode}
                      </option>
                    ))}
                  </select>
                </label>

                <label className="grid gap-1 text-sm">
                  <span className="font-semibold">
                    Due Date
                  </span>

                  <input
                    name="dueDate"
                    type="date"
                    defaultValue={indiaDateInput(task.dueDate)}
                    className="rounded-xl border bg-white p-2"
                  />
                </label>

                <label className="grid gap-1 text-sm">
                  <span className="font-semibold">
                    Estimated Hours
                  </span>

                  <input
                    name="estimatedHours"
                    type="number"
                    min="0"
                    max="999999.99"
                    step="0.25"
                    defaultValue={
                      task.estimatedHours?.toString() ?? ""
                    }
                    className="rounded-xl border bg-white p-2"
                  />
                </label>

                <label className="grid gap-1 text-sm">
                  <span className="font-semibold">
                    Actual Hours
                  </span>

                  <input
                    name="actualHours"
                    type="number"
                    min="0"
                    max="999999.99"
                    step="0.25"
                    defaultValue={
                      task.actualHours?.toString() ?? ""
                    }
                    className="rounded-xl border bg-white p-2"
                  />
                </label>

                <div className="flex items-end">
                  <button
                    type="submit"
                    className="w-full rounded-xl bg-blue-600 px-4 py-2 font-bold text-white"
                  >
                    Save Task
                  </button>
                </div>
              </form>
            </article>
          ))}
        </section>
      </main>
    </CustomerAdminShell>
  );
}
