import type { Metadata } from "next";
import Image from "next/image";
import { notFound } from "next/navigation";

import { Container } from "@/components/Container";
import { PageHeader } from "@/components/PageHeader";
import { PostCard } from "@/components/PostCard";
import { StudyCard } from "@/components/StudyCard";
import { sanityFetchList, sanityFetchOne } from "@/sanity/fetch";
import { urlFor } from "@/sanity/image";
import {
  AUTHOR_BY_SLUG_QUERY,
  AUTHOR_SLUGS_QUERY,
  type AuthorDetail,
} from "@/sanity/queries";

type Params = { slug: string };

export const dynamic = "auto";

export async function generateStaticParams(): Promise<Params[]> {
  // Returns [] when Sanity is unconfigured so Next falls back to on-demand
  // rendering and the build never blocks on missing credentials.
  const slugs = await sanityFetchList<{ slug: string }>({
    query: AUTHOR_SLUGS_QUERY,
    tags: ["author"],
  });
  return slugs.filter((s) => !!s.slug).map((s) => ({ slug: s.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { slug } = await params;
  const author = await sanityFetchOne<AuthorDetail>({
    query: AUTHOR_BY_SLUG_QUERY,
    params: { slug },
    tags: ["author", `author:${slug}`],
  });
  if (!author) return { title: "Not found" };
  return {
    title: author.name,
    description: `${author.name} · ${author.institution ?? "OrthoGlobe"}`,
  };
}

export default async function AuthorProfilePage({
  params,
}: {
  params: Promise<Params>;
}) {
  const { slug } = await params;
  const author = await sanityFetchOne<AuthorDetail>({
    query: AUTHOR_BY_SLUG_QUERY,
    params: { slug },
    tags: ["author", `author:${slug}`],
  });
  if (!author) notFound();

  const avatarUrl = author.avatar
    ? urlFor(author.avatar).width(240).height(240).fit("crop").url()
    : "";

  return (
    <>
      <PageHeader
        eyebrow="Author"
        title={author.name}
        lede={author.institution ?? ""}
      />
      <Container className="pb-24">
        <div className="grid gap-10 md:grid-cols-[240px_1fr]">
          <div className="flex flex-col items-start gap-4">
            {avatarUrl && (
              <div className="relative h-40 w-40 overflow-hidden rounded-full border border-[var(--color-line)] bg-[var(--color-mist)]">
                <Image
                  src={avatarUrl}
                  alt=""
                  fill
                  sizes="160px"
                  className="object-cover"
                />
              </div>
            )}
            {author.orcidUrl && (
              <a
                href={author.orcidUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="text-[13px] font-semibold text-[var(--color-blue)] underline underline-offset-2 hover:text-[var(--color-blue-deep)]"
              >
                ORCID profile →
              </a>
            )}
          </div>
          <div>
            {author.bio && (
              <p className="max-w-2xl text-[17px] leading-relaxed text-[var(--color-slate)]">
                {author.bio}
              </p>
            )}
          </div>
        </div>

        {author.posts.length > 0 && (
          <section className="mt-20">
            <h2 className="font-display text-[24px] font-extrabold leading-tight tracking-[-0.01em] text-[var(--color-ink)]">
              Posts by {author.name}
            </h2>
            <div className="mt-8 grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
              {author.posts.map((post) => (
                <PostCard key={post._id} post={post} />
              ))}
            </div>
          </section>
        )}

        {author.studies.length > 0 && (
          <section className="mt-20">
            <h2 className="font-display text-[24px] font-extrabold leading-tight tracking-[-0.01em] text-[var(--color-ink)]">
              Studies by {author.name}
            </h2>
            <div className="mt-8 grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
              {author.studies.map((study) => (
                <StudyCard key={study._id} study={study} />
              ))}
            </div>
          </section>
        )}

        {author.posts.length === 0 && author.studies.length === 0 && (
          <p className="mt-20 text-[15px] text-[var(--color-slate)]">
            No published content yet.
          </p>
        )}
      </Container>
    </>
  );
}
