import type { Metadata } from "next";
import { getPayload } from "payload";
import config from "@payload-config";
import Image from "next/image";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { GridOverlay, TechChip } from "@/components/site";

export const metadata: Metadata = { title: "About" };
export const dynamic = "force-dynamic";

type MediaDoc = {
  url?: string | null;
  alt: string;
  width?: number | null;
  height?: number | null;
};

type GearDoc = {
  id: string;
  name: string;
  category?: string | null;
  summary?: string | null;
  link?: string | null;
  image?: MediaDoc | string | null;
};

type FeaturedGearItem = {
  id?: string | null;
  gear?: GearDoc | string | null;
};

type TimelineItem = {
  id?: string | null;
  year: string;
  title: string;
  body?: string | null;
  tags?: { id?: string | null; label?: string | null }[] | null;
};

type SkillGroup = {
  id?: string | null;
  category: string;
  items?: { id?: string | null; label?: string | null }[] | null;
};

type AboutData = {
  intro?: {
    eyebrow?: string | null;
    headline?: string | null;
    subheadline?: string | null;
    portrait?: MediaDoc | string | null;
  } | null;
  bio?: Record<string, unknown> | null;
  timeline?: TimelineItem[] | null;
  skills?: SkillGroup[] | null;
  featuredGear?: FeaturedGearItem[] | null;
};

function isMediaDoc(val: unknown): val is MediaDoc {
  return typeof val === "object" && val !== null && "alt" in val;
}

function isGearDoc(val: unknown): val is GearDoc {
  return typeof val === "object" && val !== null && "name" in val;
}

const categoryLabels: Record<string, string> = {
  compute: "Compute",
  audio: "Audio",
  peripherals: "Peripherals",
  network: "Network",
  "dev-tools": "Dev Tools",
  other: "Other",
};

export default async function AboutPage() {
  const payload = await getPayload({ config });
  const about = (await payload.findGlobal({ slug: "about", depth: 2 })) as AboutData;

  const { intro, bio, timeline, skills, featuredGear } = about;

  const portrait = isMediaDoc(intro?.portrait) ? intro.portrait : null;

  return (
    <main className="mx-auto max-w-7xl space-y-32 px-6 py-20">
      {/* ── 1. INTRO ─────────────────────────────────────────────────── */}
      <section className="grid grid-cols-1 items-start gap-12 lg:grid-cols-12">
        {/* Text — 60% */}
        <div className="space-y-8 lg:col-span-7">
          <div className="space-y-4">
            {intro?.eyebrow && (
              <span className="label-sm block text-primary uppercase tracking-[0.2em]">
                {intro.eyebrow}
              </span>
            )}
            {intro?.headline && (
              <h1 className="display-lg leading-tight tracking-tighter text-on-surface">
                {intro.headline}
              </h1>
            )}
          </div>
          {intro?.subheadline && (
            <p className="body-lg max-w-2xl leading-relaxed text-on-surface-variant">
              {intro.subheadline}
            </p>
          )}
        </div>

        {/* Portrait — 40% */}
        <div className="relative lg:col-span-5">
          <div className="absolute inset-0 -z-10 blur-[80px] opacity-20 bg-primary/20" />
          <div className="relative aspect-square overflow-hidden rounded-md border border-outline-variant/15 bg-surface-container">
            <GridOverlay opacity={0.15} />
            {portrait?.url ? (
              <Image
                src={portrait.url}
                alt={portrait.alt}
                fill
                className="object-cover mix-blend-luminosity hover:mix-blend-normal transition-all duration-500"
                sizes="(max-width: 1024px) 100vw, 40vw"
              />
            ) : (
              <div className="absolute inset-0 flex items-center justify-center text-on-surface-variant label-sm uppercase">
                Portrait
              </div>
            )}
          </div>
        </div>
      </section>

      {/* ── 2. BIO ────────────────────────────────────────────────────── */}
      {bio && (
        <section className="space-y-8">
          <span className="label-sm block text-secondary uppercase tracking-[0.2em]">
            02 // BIO
          </span>
          <div className="body-lg max-w-3xl space-y-4 leading-relaxed text-on-surface-variant [&_h2]:headline-lg [&_h2]:text-on-surface [&_h3]:title-lg [&_h3]:text-on-surface [&_a]:text-primary [&_a]:underline [&_a:hover]:text-primary/80">
            {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
            <RichText data={bio as any} />
          </div>
        </section>
      )}

      {/* ── 3. TIMELINE ───────────────────────────────────────────────── */}
      {timeline && timeline.length > 0 && (
        <section className="space-y-8">
          <span className="label-sm block text-tertiary uppercase tracking-[0.2em]">
            03 // TIMELINE
          </span>
          <div className="space-y-0">
            {timeline.map((item, i) => (
              <div
                key={item.id ?? item.year}
                className={`grid grid-cols-1 gap-6 px-8 py-8 md:grid-cols-12 ${
                  i % 2 === 0
                    ? "bg-surface-container-low"
                    : "bg-surface-container"
                }`}
              >
                <div className="md:col-span-2">
                  <span className="label-sm font-mono text-primary">
                    {item.year}
                  </span>
                </div>
                <div className="space-y-3 md:col-span-10">
                  <h3 className="title-lg text-on-surface">{item.title}</h3>
                  {item.body && (
                    <p className="body-md text-on-surface-variant leading-relaxed">
                      {item.body}
                    </p>
                  )}
                  {item.tags && item.tags.length > 0 && (
                    <div className="flex flex-wrap gap-2 pt-1">
                      {item.tags.map((tag, ti) =>
                        tag.label ? (
                          <TechChip key={tag.id ?? ti} accent="secondary">
                            {tag.label}
                          </TechChip>
                        ) : null,
                      )}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* ── 4. SKILLS ─────────────────────────────────────────────────── */}
      {skills && skills.length > 0 && (
        <section className="space-y-8">
          <span className="label-sm block text-primary uppercase tracking-[0.2em]">
            04 // SKILLS
          </span>
          <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3">
            {skills.map((group) => (
              <div key={group.id ?? group.category} className="space-y-3">
                <h3 className="label-md uppercase text-on-surface-variant">
                  {group.category}
                </h3>
                <div className="flex flex-wrap gap-2">
                  {group.items?.map((item, ii) =>
                    item.label ? (
                      <TechChip key={item.id ?? ii} accent="tertiary">
                        {item.label}
                      </TechChip>
                    ) : null,
                  )}
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* ── 5. GEAR ───────────────────────────────────────────────────── */}
      {featuredGear && featuredGear.length > 0 && (
        <section className="space-y-8">
          <span className="label-sm block text-secondary uppercase tracking-[0.2em]">
            05 // GEAR
          </span>
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {featuredGear.map((entry) => {
              if (!isGearDoc(entry.gear)) return null;
              const gear = entry.gear;
              const img = isMediaDoc(gear.image) ? gear.image : null;

              return (
                <div
                  key={gear.id}
                  className="relative overflow-hidden rounded-md border border-outline-variant/15 bg-surface-container-low flex flex-col"
                >
                  {img?.url ? (
                    <div className="relative aspect-video w-full overflow-hidden">
                      <Image
                        src={img.url}
                        alt={img.alt}
                        fill
                        className="object-cover"
                        sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
                      />
                    </div>
                  ) : (
                    <div className="aspect-video w-full bg-surface-container" />
                  )}
                  <div className="flex flex-1 flex-col gap-3 p-5">
                    <div className="flex items-start justify-between gap-2">
                      <h3 className="title-lg text-on-surface">{gear.name}</h3>
                      {gear.category && (
                        <TechChip accent="primary">
                          {categoryLabels[gear.category] ?? gear.category}
                        </TechChip>
                      )}
                    </div>
                    {gear.summary && (
                      <p className="body-md flex-1 text-on-surface-variant leading-relaxed">
                        {gear.summary}
                      </p>
                    )}
                    {gear.link && (
                      <a
                        href={gear.link}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="label-sm mt-auto self-start text-primary hover:text-primary/80 transition-colors"
                      >
                        Learn more →
                      </a>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </section>
      )}
    </main>
  );
}
