import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { Clock, ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { getEpisode } from "@/lib/podcast.functions";

export const Route = createFileRoute("/episodes/$slug")({
  loader: async ({ params }) => {
    const result = await getEpisode({ data: params.slug });
    if (!result) throw notFound();
    return result;
  },
  head: ({ loaderData }) => {
    const episode = loaderData?.episode;
    const title = episode ? `${episode.title} — Gatavase Live Podcast` : "Episode — Gatavase";
    const description =
      episode?.summary || "A recorded episode of the Gatavase Live Podcast.";
    return {
      meta: [
        { title },
        { name: "description", content: description },
        { property: "og:title", content: title },
        { property: "og:description", content: description },
        { property: "og:type", content: "article" },
        { property: "og:url", content: `/episodes/${episode?.slug ?? ""}` },
        { name: "twitter:card", content: "summary_large_image" },
        ...(episode?.cover_image_url?.startsWith("https://")
          ? [
              { property: "og:image", content: episode.cover_image_url },
              { name: "twitter:image", content: episode.cover_image_url },
            ]
          : []),
      ],
      links: [{ rel: "canonical", href: `/episodes/${episode?.slug ?? ""}` }],
      scripts: episode
        ? [
            {
              type: "application/ld+json",
              children: JSON.stringify({
                "@context": "https://schema.org",
                "@type": "PodcastEpisode",
                name: episode.title,
                description: episode.summary,
                datePublished: episode.published_at,
                timeRequired: `PT${episode.duration_minutes}M`,
                partOfSeries: {
                  "@type": "PodcastSeries",
                  name: "Gatavase Live Podcast",
                },
                publisher: { "@type": "Organization", name: "Gatavase Corporation" },
              }),
            },
          ]
        : [],
    };
  },
  errorComponent: () => (
    <div className="mx-auto max-w-3xl px-5 py-24 text-center">
      <h1 className="text-2xl font-bold">We could not load this episode</h1>
      <Button asChild className="mt-6">
        <Link to="/episodes">Back to the archive</Link>
      </Button>
    </div>
  ),
  notFoundComponent: () => (
    <div className="mx-auto max-w-3xl px-5 py-24 text-center">
      <h1 className="text-2xl font-bold">Episode not found</h1>
      <Button asChild className="mt-6">
        <Link to="/episodes">Back to the archive</Link>
      </Button>
    </div>
  ),
  component: EpisodePage,
});

function EpisodePage() {
  const { episode, guests } = Route.useLoaderData();

  return (
    <article className="mx-auto max-w-4xl px-5 py-14">
      <Link
        to="/episodes"
        className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
      >
        <ArrowLeft className="size-4" /> Episode archive
      </Link>

      <h1 className="mt-6 text-3xl font-bold md:text-4xl">{episode.title}</h1>
      <p className="mt-3 flex flex-wrap items-center gap-4 text-xs text-muted-foreground">
        <span>
          {new Date(episode.published_at).toLocaleDateString(undefined, {
            year: "numeric",
            month: "long",
            day: "numeric",
          })}
        </span>
        <span className="inline-flex items-center gap-1.5">
          <Clock className="size-3.5" /> {episode.duration_minutes} min
        </span>
      </p>
      <p className="mt-5 text-lg leading-relaxed text-muted-foreground">{episode.summary}</p>

      {episode.video_url && (
        <div className="panel mt-8 overflow-hidden">
          <div className="aspect-video w-full bg-black">
            <iframe
              src={episode.video_url}
              title={episode.title}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture"
              allowFullScreen
              className="size-full"
            />
          </div>
        </div>
      )}

      {episode.show_notes && (
        <section className="mt-10">
          <h2 className="text-xl font-semibold">Show notes</h2>
          <p className="mt-3 whitespace-pre-wrap text-sm leading-relaxed text-muted-foreground">
            {episode.show_notes}
          </p>
        </section>
      )}

      {guests.length > 0 && (
        <section className="mt-10">
          <h2 className="text-xl font-semibold">Guests</h2>
          <div className="mt-4 grid gap-4 sm:grid-cols-2">
            {guests.map((g) => (
              <div key={g.id} className="panel p-5">
                <p className="font-semibold">{g.name}</p>
                <p className="text-xs text-primary">{g.role_title}</p>
                <p className="mt-2 text-sm text-muted-foreground">{g.bio}</p>
              </div>
            ))}
          </div>
        </section>
      )}

      <div className="mt-12 flex flex-wrap gap-3">
        <Button asChild>
          <Link to="/live-podcast">Watch the next live show</Link>
        </Button>
        <Button asChild variant="outline">
          <Link to="/contact">Apply as a guest</Link>
        </Button>
      </div>
    </article>
  );
}
