import Link from "next/link";
import { ProjectType } from "@prisma/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import AdminPageHeader from "@/components/admin/admin-page-header";
import { deleteProject } from "@/app/admin/(protected)/projects/actions";
import { prisma } from "@/lib/db";
import { projectTypeFilterSchema } from "@/lib/validations/project";

const typeLabels: Record<ProjectType, string> = {
  PORTFOLIO: "Portfolio",
  APP: "App",
  WEBSITE: "Website",
  DESIGN: "Design",
};

type ProjectsPageProps = {
  searchParams: { type?: string; error?: string };
};

function getErrorMessage(error?: string) {
  if (error === "invalid-id") return "The selected project id is invalid.";
  if (error === "not-found") return "The selected project no longer exists.";
  if (error === "delete-failed") return "The project could not be deleted.";
  return null;
}

export default async function ProjectsPage({ searchParams }: ProjectsPageProps) {
  const type = projectTypeFilterSchema.safeParse(searchParams.type);
  const selectedType = type.success ? type.data : undefined;
  const projects = await prisma.project.findMany({
    where: selectedType ? { type: selectedType } : undefined,
    orderBy: [{ sortOrder: "asc" }, { updatedAt: "desc" }],
    include: { category: { select: { nameEn: true, nameAr: true } } },
  });
  const errorMessage = getErrorMessage(searchParams.error);

  return (
    <div className="mx-auto w-full max-w-7xl">
      <AdminPageHeader
        title="Projects"
        description="Manage portfolio work, apps, websites, designs, and the project records used by public pages."
        actions={
          <Button asChild>
            <Link href="/admin/projects/new">New project</Link>
          </Button>
        }
      />

      {errorMessage ? (
        <p className="mb-6 rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {errorMessage}
        </p>
      ) : null}

      <div className="mb-6 flex flex-wrap gap-2">
        <Button asChild size="sm" variant={!selectedType ? "default" : "outline"}>
          <Link href="/admin/projects">All</Link>
        </Button>
        {Object.entries(typeLabels).map(([value, label]) => (
          <Button key={value} asChild size="sm" variant={selectedType === value ? "default" : "outline"}>
            <Link href={`/admin/projects?type=${value}`}>{label}</Link>
          </Button>
        ))}
      </div>

      {projects.length === 0 ? (
        <Card>
          <CardContent className="p-6">
            <p className="text-sm text-muted-foreground">No projects match this filter yet.</p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {projects.map((project) => (
            <Card key={project.id}>
              <CardHeader className="flex-row items-start justify-between gap-4 space-y-0">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.14em] text-brand-2">{typeLabels[project.type]}</p>
                  <CardTitle className="mt-2 text-lg">{project.titleEn}</CardTitle>
                  <p className="mt-1 text-sm text-muted-foreground" dir="rtl">
                    {project.titleAr}
                  </p>
                </div>
                <span className="rounded-pill border border-border px-2 py-1 text-xs text-muted-foreground">{project.status}</span>
              </CardHeader>
              <CardContent>
                <p className="text-xs text-muted-foreground">/{project.slug}</p>
                <p className="mt-2 text-sm text-muted-foreground">
                  {project.category ? `${project.category.nameEn} · ${project.category.nameAr}` : "No category"}
                </p>
                <p className="mt-2 text-xs text-muted-foreground">
                  {project.images.length} images · {project.technologies.length} technologies
                </p>
                <div className="mt-5 flex items-center gap-2">
                  <Button asChild size="sm" variant="outline">
                    <Link href={`/admin/projects/${project.id}/edit`}>Edit</Link>
                  </Button>
                  <form action={deleteProject}>
                    <input type="hidden" name="projectId" value={project.id} />
                    <Button type="submit" size="sm" variant="ghost">
                      Delete
                    </Button>
                  </form>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
