import Link from "next/link";
import { notFound } from "next/navigation";
import { Button } from "@/components/ui/button";
import AdminPageHeader from "@/components/admin/admin-page-header";
import ProjectForm from "@/components/admin/project-form";
import { prisma } from "@/lib/db";
import type { ProjectInput } from "@/lib/validations/project";

export default async function EditProjectPage({ params }: { params: { id: string } }) {
  const [project, categories] = await Promise.all([
    prisma.project.findUnique({ where: { id: params.id } }),
    prisma.category.findMany({
      where: { kind: "PROJECT" },
      orderBy: [{ order: "asc" }, { nameEn: "asc" }],
      select: { id: true, nameAr: true, nameEn: true },
    }),
  ]);

  if (!project) {
    notFound();
  }

  const defaultValues: ProjectInput = {
    type: project.type,
    slug: project.slug,
    titleAr: project.titleAr,
    titleEn: project.titleEn,
    summaryAr: project.summaryAr ?? "",
    summaryEn: project.summaryEn ?? "",
    descAr: project.descAr ?? "",
    descEn: project.descEn ?? "",
    coverImage: project.coverImage ?? "",
    images: project.images,
    technologies: project.technologies,
    externalUrl: project.externalUrl ?? "",
    repoUrl: project.repoUrl ?? "",
    platform: project.platform ?? "",
    appStoreUrl: project.appStoreUrl ?? "",
    testflightUrl: project.testflightUrl ?? "",
    appVersion: project.appVersion ?? "",
    supportUrl: project.supportUrl ?? "",
    appPrivacyUrl: project.appPrivacyUrl ?? "",
    status: project.status,
    isFeatured: project.isFeatured,
    sortOrder: project.sortOrder,
    categoryId: project.categoryId ?? "",
  };

  return (
    <div className="mx-auto w-full max-w-7xl">
      <AdminPageHeader
        title={`Edit ${project.titleEn}`}
        description="Update the project details, media paths, category, and public visibility settings."
        actions={
          <Button asChild variant="outline">
            <Link href="/admin/projects">Back to projects</Link>
          </Button>
        }
      />
      <ProjectForm mode="edit" projectId={project.id} categories={categories} defaultValues={defaultValues} />
    </div>
  );
}
