import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { getDictionary, pick } from "@/i18n";
import { sanityFetch, slugStaticParams } from "@/sanity/client";
import { POST_QUERY, POST_SLUGS_QUERY, POSTS_QUERY } from "@/sanity/queries";
import { Container, SectionHeading } from "@/components/ui";
import { Reveal } from "@/components/reveal";
import { SanityImage } from "@/components/sanity-image";
import { RichText } from "@/components/portable-text";
import { PostCard } from "@/components/cards";
import { formatDate } from "@/lib/format";

/* eslint-disable @typescript-eslint/no-explicit-any */

export async function generateStaticParams() {
  return slugStaticParams(POST_SLUGS_QUERY);
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale, slug } = await params;
  const post = await sanityFetch<any>(POST_QUERY, { slug }, null);
  if (!post) return {};
  return { title: pick(post.title, locale), description: pick(post.excerpt, locale) };
}

export default async function PostPage({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale, slug } = await params;
  const dict = getDictionary(locale);
  const [post, allPosts] = await Promise.all([
    sanityFetch<any>(POST_QUERY, { slug }, null),
    sanityFetch<any[]>(POSTS_QUERY, {}, []),
  ]);
  if (!post) notFound();

  const others = (allPosts || []).filter((p) => p.slug?.current !== slug).slice(0, 3);

  return (
    <article>
      {/* Header */}
      <Container narrow>
        <div className="pt-12 text-center sm:pt-16">
          <Link
            href={`/${locale}/blog/`}
            className="inline-flex items-center gap-1.5 text-sm font-semibold text-brand-bright transition hover:gap-2.5"
          >
            <ArrowLeft className="size-4" />
            {dict.nav.blog}
          </Link>
          <p className="mt-8 text-xs font-semibold uppercase tracking-[0.16em] text-brand-bright">
            {formatDate(post.publishedAt, locale)}
          </p>
          <h1 className="mx-auto mt-3 max-w-3xl text-balance text-4xl leading-tight tracking-tight sm:text-5xl">
            {pick(post.title, locale)}
          </h1>
          {post.author?.name && (
            <div className="mt-6 flex items-center justify-center gap-3">
              {post.author.image && (
                <span className="h-10 w-10 overflow-hidden rounded-full bg-brand/10">
                  <SanityImage
                    image={post.author.image}
                    alt={post.author.name}
                    widths={[80, 120]}
                    sizes="40px"
                    className="h-full w-full object-cover"
                  />
                </span>
              )}
              <span className="text-left text-sm">
                <span className="block font-semibold text-ink">{post.author.name}</span>
                {post.author.role && (
                  <span className="block text-muted">{pick(post.author.role, locale)}</span>
                )}
              </span>
            </div>
          )}
        </div>
      </Container>

      {/* Cover (wider than the body column) */}
      {post.coverImage && (
        <div className="mx-auto mt-12 max-w-5xl px-5 sm:px-8">
          <Reveal>
            <div className="overflow-hidden rounded-[2rem] shadow-xl">
              <SanityImage
                image={post.coverImage}
                alt={pick(post.title, locale) || ""}
                priority
                sizes="(min-width: 1024px) 64rem, 100vw"
                className="aspect-[16/9] w-full object-cover"
              />
            </div>
          </Reveal>
        </div>
      )}

      {/* Body */}
      <Container narrow>
        <div className="py-14">
          <RichText value={pick(post.body, locale)} />
        </div>
      </Container>

      {/* Related */}
      {others.length > 0 && (
        <section className="border-t border-line bg-surface py-16 sm:py-20">
          <Container>
            <SectionHeading
              title={dict.blog.readingFrom}
              action={{ href: `/${locale}/blog/`, label: dict.cta.viewAll }}
            />
            <div className="mt-10 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {others.map((p, i) => (
                <Reveal key={p._id} delay={i * 0.06}>
                  <PostCard post={p} locale={locale} dict={dict} />
                </Reveal>
              ))}
            </div>
          </Container>
        </section>
      )}
    </article>
  );
}
