import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { VideoEmbed } from "@/components/site/VideoEmbed";
import { prisma } from "@/lib/prisma";
import { formatDate, siteUrl } from "@/lib/utils";

type PageProps = {
  params: Promise<{ slug: string }>;
};

function seoKeywords(value?: string | null) {
  return value?.split(",").map((keyword) => keyword.trim()).filter(Boolean);
}

function renderDescriptionWithHashtags(description: string) {
  return description.split(/(\s+|#[\p{L}\p{N}_-]+)/gu).map((part, index) => {
    if (part.startsWith("#")) {
      return <span className="video-hashtag" key={`${part}-${index}`}>{part}</span>;
    }

    return part;
  });
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const video = await prisma.video.findUnique({ where: { slug } });

  if (!video) {
    return {};
  }

  return {
    title: video.seoTitle ?? video.title,
    description: video.seoDescription ?? video.description,
    keywords: seoKeywords(video.seoKeywords),
    alternates: { canonical: siteUrl(`/videos/${video.slug}`) },
    openGraph: {
      title: video.seoTitle ?? video.title,
      description: video.seoDescription ?? video.description,
      images: video.thumbnail ? [{ url: video.thumbnail, alt: video.title }] : undefined,
      url: siteUrl(`/videos/${video.slug}`),
      type: "video.other"
    },
    twitter: {
      card: video.thumbnail ? "summary_large_image" : "summary",
      title: video.seoTitle ?? video.title,
      description: video.seoDescription ?? video.description,
      images: video.thumbnail ? [video.thumbnail] : undefined
    }
  };
}

export default async function VideoDetailPage({ params }: PageProps) {
  const { slug } = await params;
  const video = await prisma.video.findUnique({
    where: { slug },
    include: { category: true }
  });

  if (!video || video.status !== "PUBLISHED" || video.approvalStatus !== "APPROVED") {
    notFound();
  }

  return (
    <main className="container" style={{ padding: "4rem 1.25rem" }}>
      <script
        dangerouslySetInnerHTML={{
          __html: JSON.stringify({
            "@context": "https://schema.org",
            "@type": "VideoObject",
            description: video.seoDescription ?? video.description,
            embedUrl: `https://www.youtube.com/embed/${video.youtubeId}`,
            name: video.seoTitle ?? video.title,
            thumbnailUrl: video.thumbnail ? [siteUrl(video.thumbnail)] : [`https://img.youtube.com/vi/${video.youtubeId}/hqdefault.jpg`],
            uploadDate: video.publishedAt?.toISOString() ?? video.createdAt.toISOString()
          })
        }}
        type="application/ld+json"
      />
      <div className="section-head">
        <div>
          {video.category ? <span className="pill">{video.category.name}</span> : null}
          <h1 className="section-title">{video.title}</h1>
          <p className="muted">{formatDate(video.publishedAt)}</p>
        </div>
      </div>
      <VideoEmbed isShort={video.kind === "SHORT"} title={video.title} youtubeId={video.youtubeId} />
      <section className="youtube-description-box" aria-label="Video description">
        <div className="youtube-description-meta">
          <strong>{formatDate(video.publishedAt)}</strong>
          {video.category ? <span>{video.category.name}</span> : null}
          <span>Just Chill Nepal</span>
        </div>
        <p className="video-full-description">
          {renderDescriptionWithHashtags(video.description)}
        </p>
      </section>
    </main>
  );
}
