import type { SanityDocument } from "next-sanity";
import { PortableText } from "next-sanity";
import { client } from "@/sanity/lib/client";
import { urlFor } from "@/sanity/lib/image";
import { TEMPLATES_QUERY } from "@/sanity/lib/queries";

export const metadata = {
  title: "Printing Templates | Cellar Labels",
};

const options = { next: { revalidate: 60 } };

export default async function TemplatesPage() {
  const templates = await client.fetch<SanityDocument[]>(
    TEMPLATES_QUERY,
    {},
    options,
  );

  return (
    <main className="mx-auto max-w-3xl px-6 py-16">
      <h1 className="font-heading text-4xl font-semibold text-terracotta">
        Printing Templates
      </h1>

      {templates.length === 0 ? (
        <p className="mt-8 text-charcoal/60">
          No printing templates published yet.
        </p>
      ) : (
        <div className="mt-10 flex flex-col gap-16">
          {templates.map((template) => {
            const coverImageUrl = template.coverImage
              ? urlFor(template.coverImage).width(1200).height(675).url()
              : null;

            return (
              <article key={template._id}>
                <h2 className="font-heading text-2xl font-semibold text-charcoal">
                  {template.title}
                </h2>
                {coverImageUrl && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={coverImageUrl}
                    alt=""
                    className="mt-4 aspect-video w-full rounded-lg object-cover"
                  />
                )}
                <div className="prose prose-p:text-charcoal prose-headings:font-heading prose-headings:text-charcoal mt-4 max-w-none">
                  {Array.isArray(template.body) && (
                    <PortableText value={template.body} />
                  )}
                </div>
              </article>
            );
          })}
        </div>
      )}
    </main>
  );
}
