import type { Metadata } from "next"
import { connection } from "next/server"
import { MDXRemote } from "next-mdx-remote/rsc"
import type { ComponentProps, ReactNode } from "react"

import { auth } from "@/auth"
import ProGate from "@/components/report/ProGate"
import RelatedReports from "@/components/report/RelatedReports"
import ReportHero from "@/components/report/ReportHero"
import TableOfContents from "@/components/report/TableOfContents"
import { getAllReports, getReportBySlug } from "@/lib/mdx"

type ReportPageProps = {
  params: Promise<{
    slug: string
  }>
}

export const dynamic = "force-dynamic"

function formatDate(date: string) {
  return new Date(date).toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  })
}

function getTextContent(children: ReactNode): string {
  if (typeof children === "string" || typeof children === "number") {
    return String(children)
  }

  if (Array.isArray(children)) {
    return children.map((child) => getTextContent(child)).join("")
  }

  return ""
}

function slugify(children: ReactNode) {
  return getTextContent(children)
    .toLowerCase()
    .replace(/\s+/g, "-")
    .replace(/[^a-z0-9-]/g, "")
}

const mdxComponents = {
  h2: ({ children, ...props }: ComponentProps<"h2">) => (
    <h2
      {...props}
      id={slugify(children)}
      className="mb-4 mt-10 scroll-mt-24 border-b border-[var(--color-border)] pb-2 font-serif text-[1.6rem] font-normal text-[var(--color-text-primary)]"
    >
      {children}
    </h2>
  ),
  h3: ({ children, ...props }: ComponentProps<"h3">) => (
    <h3
      {...props}
      id={slugify(children)}
      className="mb-3 mt-8 scroll-mt-24 font-serif text-xl font-normal text-[var(--color-text-primary)]"
    >
      {children}
    </h3>
  ),
  p: ({ children, ...props }: ComponentProps<"p">) => (
    <p
      {...props}
      className="mb-5 text-base leading-[1.8] text-[var(--color-text-secondary)]"
    >
      {children}
    </p>
  ),
  a: ({ children, ...props }: ComponentProps<"a">) => (
    <a {...props} className="text-[var(--color-accent)] hover:underline">
      {children}
    </a>
  ),
  strong: ({ children, ...props }: ComponentProps<"strong">) => (
    <strong {...props} className="font-semibold text-[var(--color-text-primary)]">
      {children}
    </strong>
  ),
  blockquote: ({ children, ...props }: ComponentProps<"blockquote">) => (
    <blockquote
      {...props}
      className="my-4 rounded-r border-l-[3px] border-[var(--color-accent)] bg-[var(--color-surface)] py-2 pl-4 italic text-[var(--color-text-secondary)]"
    >
      {children}
    </blockquote>
  ),
  ul: ({ children, ...props }: ComponentProps<"ul">) => (
    <ul
      {...props}
      className="mb-4 list-disc pl-6 text-[15px] leading-[1.8] text-[var(--color-text-secondary)]"
    >
      {children}
    </ul>
  ),
  ol: ({ children, ...props }: ComponentProps<"ol">) => (
    <ol
      {...props}
      className="mb-4 list-decimal pl-6 text-[15px] leading-[1.8] text-[var(--color-text-secondary)]"
    >
      {children}
    </ol>
  ),
  li: ({ children, ...props }: ComponentProps<"li">) => (
    <li {...props} className="mb-[0.4rem]">
      {children}
    </li>
  ),
  code: ({ children, ...props }: ComponentProps<"code">) => (
    <code
      {...props}
      className="rounded bg-[var(--color-surface)] px-1.5 py-0.5 font-mono text-[13px] text-[var(--color-accent)]"
    >
      {children}
    </code>
  ),
  pre: ({ children, ...props }: ComponentProps<"pre">) => (
    <pre
      {...props}
      className="mb-4 overflow-x-auto rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-4"
    >
      {children}
    </pre>
  ),
  hr: (props: ComponentProps<"hr">) => (
    <hr {...props} className="my-8 border-[var(--color-border)]" />
  ),
}

export async function generateMetadata({
  params,
}: ReportPageProps): Promise<Metadata> {
  try {
    const { slug } = await params
    const report = getReportBySlug(slug)
    const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://parallax.com"

    return {
      title: report.title,
      description: report.subtitle,
      keywords: [
        report.region,
        report.topic,
        "geopolitics",
        "analysis",
        "foreign policy",
      ],
      authors: [{ name: "Parallax" }],
      openGraph: {
        type: "article",
        locale: "en_GB",
        url: `${baseUrl}/${report.slug}`,
        siteName: "Parallax",
        title: report.title,
        description: report.subtitle,
        publishedTime: report.publishedAt,
        tags: [report.region, report.topic],
        images: [
          {
            url: report.coverImage,
            width: 1200,
            height: 630,
            alt: report.title,
          },
        ],
      },
      twitter: {
        card: "summary_large_image",
        title: report.title,
        description: report.subtitle,
        images: [report.coverImage],
      },
      alternates: {
        canonical: `${baseUrl}/${report.slug}`,
      },
    }
  } catch {
    return {
      title: "Report not found",
      description: "This report does not exist.",
    }
  }
}

export default async function ReportPage({ params }: ReportPageProps) {
  const { slug } = await params
  const report = getReportBySlug(slug)
  const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://parallax.com"
  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Article",
    headline: report.title,
    description: report.subtitle,
    image: report.coverImage,
    datePublished: report.publishedAt,
    dateModified: report.publishedAt,
    author: {
      "@type": "Organization",
      name: "Parallax",
      url: baseUrl,
    },
    publisher: {
      "@type": "Organization",
      name: "Parallax",
      url: baseUrl,
      logo: {
        "@type": "ImageObject",
        url: `${baseUrl}/icon.svg`,
      },
    },
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": `${baseUrl}/${report.slug}`,
    },
    articleSection: report.region,
    keywords: `${report.region}, ${report.topic}, geopolitics`,
    isAccessibleForFree: !report.isPro,
    ...(report.isPro && {
      isPartOf: {
        "@type": ["CreativeWork", "Product"],
        name: "Parallax Pro",
        productID: "parallax:pro",
      },
    }),
  }

  await connection()
  const session = await auth()
  const userRole = session?.user?.role ?? "free"
  const canAccessPro = userRole === "admin" || userRole === "pro"
  const relatedReports = getAllReports()
    .filter(
      (relatedReport) =>
        relatedReport.region === report.region && relatedReport.slug !== slug,
    )
    .slice(0, 3)

  return (
    <main className="w-full bg-[var(--color-bg)]">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <ReportHero report={report} canAccessPro={canAccessPro} />

      <div className="mx-auto grid max-w-[1200px] gap-12 px-6 py-12 lg:grid-cols-[1fr_300px]">
        <article>
          {report.isPro && !canAccessPro ? (
            <ProGate />
          ) : (
            <div id="report-body">
              <MDXRemote
                source={report.content}
                components={mdxComponents}
                options={{
                  mdxOptions: {
                    format: "mdx",
                    remarkPlugins: [],
                    rehypePlugins: [],
                  },
                  parseFrontmatter: false,
                }}
              />
            </div>
          )}

          <div className="mt-10 border-t border-[var(--color-border)] pt-5 text-[13px] text-[var(--color-text-secondary)]">
            Published {formatDate(report.publishedAt)}
          </div>
        </article>

        <aside className="hidden lg:block">
          <div className="sticky top-24 space-y-8">
            <TableOfContents />
            <RelatedReports reports={relatedReports} />
          </div>
        </aside>
      </div>
    </main>
  )
}
