import BreadNavigator from "@/components/bread-navigator";
import { Button } from "@/components/ui/button";
import { hasPermission, Role } from "@/lib/validation/permissions";
import { auth } from "@/server/auth";
import { api } from "@/trpc/server";
import { Edit } from "lucide-react";
import { notFound } from "next/navigation";
import React from "react";

import { appRoutes } from "@/config";
import Link from "next/link";
import { AspectRatio } from "@/components/ui/aspect-ratio";
import { CATEGORY_BANNER_ASPECT_RATIO } from "@/components/category/category-form";
import Image from "next/image";
import ArticleGrid from "@/components/article/grid/article-grid";

export type CategoryPageProps = { params: Promise<{ slug: string }> };

async function Page({ params }: CategoryPageProps) {
  const { slug } = await params;
  const category = await api.category.get({
    slug,
    with: {
      articles: true,
    },
  });

  if (!category) return notFound();

  const session = await auth();
  const isEditor = session?.user
    ? hasPermission(session.user.role, Role.EDITOR)
    : false;
  return (
    <>
      <div className="flex w-full items-center justify-between">
        <BreadNavigator
          className="w-full"
          links={[
            { label: "Kategorie", href: appRoutes.allCategories },
            {
              label: category.name!,
              href: appRoutes.category(category.name!),
            },
          ]}
        />

        {isEditor && (
          <Button asChild>
            <Link href={appRoutes.editCategory(slug)}>
              <Edit className="size-4" />
              <span>Bearbeiten</span>
            </Link>
          </Button>
        )}
      </div>
      {category.image?.length ? (
        <AspectRatio
          ratio={CATEGORY_BANNER_ASPECT_RATIO}
          className="w-full bg-muted"
        >
          <Image
            src={category.image}
            alt="Kategorie-bild"
            fill
            className="h-full w-full rounded-md object-cover"
          />
        </AspectRatio>
      ) : null}
      <h1 className="text-3xl font-bold capitalize">{category.name}</h1>
      <p className="text-muted-foreground">
        {category.description ?? "keine Beschreibung"}
      </p>

      {category?.articles?.length ? (
        <ArticleGrid articles={category.articles} />
      ) : (
        <p className="text-muted-foreground">
          Noch keine Artikel in dieser Kategorie.
        </p>
      )}
    </>
  );
}

export default Page;
