import { notFound } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { getProjectBySlug } from "@/lib/data/projects";
import { getIssues, getProjectUsers } from "@/lib/data/issues";
import { getFeatures } from "@/lib/data/features";
import { ReviewTable } from "@/components/review-table";
import { IssuesTable } from "@/components/issues-table";
import { FeaturesTable } from "@/components/features-table";
import { ProjectHeader } from "@/components/project-header";

export default async function ProjectPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const supabase = await createClient();

  const project = await getProjectBySlug(supabase, slug);
  if (!project) {
    notFound();
  }

  const [{ data: userData }, issues, users, features] = await Promise.all([
    supabase.auth.getUser(),
    getIssues(supabase, project.id),
    getProjectUsers(supabase),
    getFeatures(supabase, project.id),
  ]);
  const currentUserEmail = userData.user?.email ?? null;
  const currentUserId = userData.user?.id ?? null;

  return (
    <>
      <ProjectHeader
        projectName={project.name}
        projectId={project.id}
        currentUserEmail={currentUserEmail}
        currentUserId={currentUserId}
      />

      <div className="mx-auto w-full max-w-6xl px-4 py-8 sm:px-6">
        <section id="general-issues" className="scroll-mt-16">
          <IssuesTable
            projectId={project.id}
            initialIssues={issues}
            users={users}
            currentUserEmail={currentUserEmail}
          />
        </section>

        <section id="page-reviews" className="scroll-mt-16">
          <h2 className="mb-3 text-lg font-semibold tracking-tight">
            Page Reviews
          </h2>
          <ReviewTable
            projectId={project.id}
            initialPages={project.pages}
            currentUserEmail={currentUserEmail}
            initialStagingDomain={project.staging_domain}
            initialLiveDomain={project.live_domain}
            users={users}
          />
        </section>

        <section id="features" className="mt-10 scroll-mt-16">
          <FeaturesTable
            projectId={project.id}
            initialFeatures={features}
            currentUserEmail={currentUserEmail}
            users={users}
          />
        </section>
      </div>
    </>
  );
}
