import { getServerSession } from "next-auth";
import Link from "next/link";
import { authOptions } from "../../lib/auth/options";
import { prisma } from "../../lib/db/prisma";
import { ProjectForm } from "./project-form";
import { ProjectActions } from "./project-actions";

type ProjectSearchParams = {
  status?: string;
};

function projectStatusHref(status: string) {
  return `/admin/projects?status=${status}`;
}

export default async function ProjectsPage({ searchParams }: { searchParams: ProjectSearchParams }) {
  const session = await getServerSession(authOptions);
  const where = session?.user.systemRole === "SYSTEM_ADMIN" ? {} : { organizationId: session?.user.organizationId! };
  const status = searchParams.status ?? "active";
  const projectWhere = {
    ...where,
    ...(status === "archived" ? { isArchived: true } : status === "all" ? {} : { isArchived: false })
  };
  const [projects, users] = await Promise.all([
    prisma.project.findMany({ where: projectWhere, include: { users: true, _count: { select: { timeEntries: true } } }, orderBy: { createdAt: "desc" } }),
    prisma.user.findMany({ where, orderBy: { name: "asc" } })
  ]);

  return (
    <div>
      <h1 className="text-3xl font-semibold">Projects</h1>
      <p className="mt-2 text-slate-600">Every organization starts with a Default Project and can add more work buckets.</p>
      <section className="mt-6 grid gap-5 lg:grid-cols-[1fr_360px]">
        <div className="rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <h2 className="text-lg font-semibold">Project list</h2>
            <div className="flex rounded-lg border border-slate-200 bg-white p-1 text-xs font-semibold">
              {["active", "archived", "all"].map((item) => (
                <Link className={`rounded-md px-3 py-1 ${status === item ? "bg-brand-primary text-white" : "text-slate-600"}`} href={projectStatusHref(item)} key={item}>
                  {item[0].toUpperCase() + item.slice(1)}
                </Link>
              ))}
            </div>
          </div>
          <div className="mt-4 grid gap-2">
            {projects.map((project) => (
              <div className="grid gap-2 rounded-lg bg-brand-paper p-3 dark:bg-slate-900 md:grid-cols-[1fr_auto]" key={project.id}>
                <div>
                  <div className="flex flex-wrap items-center gap-2">
                    <Link className="font-medium text-brand-secondary" href={`/admin/projects/${project.id}`}>{project.name}</Link>
                    {project.isDefault ? <span className="rounded-lg bg-brand-tertiary px-2 py-1 text-xs font-semibold text-brand-ink">Default</span> : null}
                    {project.isArchived ? <span className="rounded-lg bg-slate-200 px-2 py-1 text-xs font-semibold text-slate-700">Archived</span> : null}
                    {project._count.timeEntries ? <span className="text-xs text-slate-500">{project._count.timeEntries} entries</span> : null}
                  </div>
                  <p className="mt-1 text-sm text-slate-500">Assigned: {project.users.map((user) => user.name ?? user.email).join(", ") || "No users"}</p>
                </div>
                <ProjectActions id={project.id} isDefault={project.isDefault} />
              </div>
            ))}
            {!projects.length ? <p className="rounded-lg bg-brand-paper p-4 text-sm text-slate-600">No {status} projects found.</p> : null}
          </div>
        </div>
        <ProjectForm users={users} />
      </section>
    </div>
  );
}
