import { metadata } from '@/app/metadata'
import { ImageWrapper } from '@/components/content/ImageWrapper'
import { ShareLinks } from '@/components/post/ShareLinks'
import { TableOfContents } from '@/components/post/TableOfContents'
import { getAllPostSlugs, getNextAndPreviousPosts, getPostBySlug } from '@/lib/posts'
import { slugify } from '@/utils/slug'
import { ArrowLeft, ArrowRight, Pencil, SendHorizonal } from 'lucide-react'
import type { Metadata } from 'next'
import Link from 'next/link'

export async function generateStaticParams() {
  return getAllPostSlugs().map((slug) => ({ slug }))
}

export const dynamicParams = false

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>
}): Promise<Metadata> {
  const { slug } = await params
  const { meta } = await getPostBySlug(slug)
  return {
    title: `${meta.title} | ${metadata.title!.toString()}`,
    description: meta.description,
    openGraph: {
      type: 'article',
      title: `${meta.title} | ${metadata.title!.toString()}`,
      description: meta.description,
      url: process.env.SITE_URL + `/posts/${slug}`,
      images: meta.coverImage ? [meta.coverImage] : undefined,
      tags: meta.tags,
      ...(meta.updated && { modifiedTime: new Date(meta.updated).toISOString() }),
      siteName: metadata.title!.toString(),
    },
  }
}

export default async function Post({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const { meta, content, tableOfContents } = await getPostBySlug(slug)
  const { next, previous } = getNextAndPreviousPosts(slug)

  return (
    <main className="flex w-full">
      <article className="max-w-3xl 2xl:max-w-4xl mx-auto px-4 py-8 mb-8 lg:py-16 min-w-0">
        {meta.category && (
          <Link
            href={`/categories/${slugify(meta.category)}`}
            className="text-accent hover:underline font-sm mb-2 inline-block"
          >
            {meta.category}
          </Link>
        )}
        <h1 className="text-4xl font-bold mb-4">{meta.title}</h1>
        <div className="flex justify-between md:justify-normal items-center gap-2 text-fg-dim mb-4 border-y border-border py-2 px-2 md:px-4 text-sm">
          <div className="flex items-center gap-2">
            <span className="hidden md:inline">Posted</span>
            <span className="md:hidden">
              <SendHorizonal className="w-3 h-3" />
            </span>
            <time
              dateTime={meta.date}
              title={new Date(meta.date).toLocaleString()}
              className="font-semibold"
            >
              {new Date(meta.date).toLocaleDateString(undefined, {
                day: 'numeric',
                month: 'short',
                year: 'numeric',
              })}
            </time>
          </div>
          <span className="hidden md:inline">&middot;</span>
          {meta.updated && (
            <>
              <div className="flex items-center gap-2">
                <span className="hidden md:inline">Updated</span>
                <span className="md:hidden">
                  <Pencil className="w-3 h-3" />
                </span>
                <time
                  dateTime={meta.updated}
                  title={new Date(meta.updated).toLocaleString()}
                  className="font-semibold"
                >
                  {new Date(meta.updated).toLocaleDateString(undefined, {
                    day: 'numeric',
                    month: 'short',
                    year: 'numeric',
                  })}
                </time>
              </div>
              <span className="hidden md:inline">&middot;</span>
            </>
          )}
          <span>{meta.readingTimeText}</span>
        </div>
        <p className="text-fg text-lg mb-4">{meta.description}</p>
        {process.env.NODE_ENV === 'development' && (
          <span className="text-fg-dim text-sm mb-4 block">
            Description has {meta.description.length} characters, which is{' '}
            {meta.description.length < 120
              ? 'too short'
              : meta.description.length > 160
                ? 'too long'
                : 'just right'}{' '}
            for SEO.
          </span>
        )}
        {meta.coverImage && <ImageWrapper src={meta.coverImage} alt={meta.coverImageAlt} />}
        <div className="prose">{content}</div>

        {meta.tags && (
          <div className="mt-6 border-t border-border pt-4 flex gap-2 items-center flex-wrap">
            <h2 className="text-lg font-bold">Tags</h2>
            <div className="flex flex-wrap gap-1">
              {meta.tags.map((tag) => (
                <Link
                  key={tag}
                  href={`/tags/${slugify(tag)}`}
                  className="bg-accent/20 text-accent px-3 py-1 rounded-full text-xs hover:bg-accent/30 transition-colors"
                >
                  {tag}
                </Link>
              ))}
            </div>
          </div>
        )}

        <div className="mt-8 mx-auto flex">
          <ShareLinks
            url={process.env.SITE_URL + `/posts/${slug}`}
            title={meta.title}
            description={meta.description}
          />
        </div>

        <div className="mt-12 grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4 border-t border-border pt-8">
          {previous ? (
            <Link
              href={`/posts/${previous.slug}`}
              className="group flex flex-col gap-1 rounded-lg p-4 transition-colors hover:bg-fg/10 active:bg-fg/15"
            >
              <span className="flex items-center gap-1 text-xs text-fg-dim uppercase tracking-wide">
                <ArrowLeft className="w-3 h-3 shrink-0 transition-transform group-hover:-translate-x-1" />
                Previous
              </span>
              <span className="text-accent font-medium group-hover:underline line-clamp-2">
                {previous.title}
              </span>
            </Link>
          ) : (
            <div className="hidden sm:block" />
          )}

          {next ? (
            <Link
              href={`/posts/${next.slug}`}
              className="group flex flex-col gap-1 rounded-lg p-4 transition-colors hover:bg-fg/10 active:bg-fg/15 sm:text-right"
            >
              <span className="flex items-center gap-1 text-xs text-fg-dim uppercase tracking-wide sm:justify-end">
                Next
                <ArrowRight className="w-3 h-3 shrink-0 transition-transform group-hover:translate-x-1" />
              </span>
              <span className="text-accent font-medium group-hover:underline line-clamp-2">
                {next.title}
              </span>
            </Link>
          ) : (
            <div className="hidden sm:block" />
          )}
        </div>
      </article>

      <TableOfContents items={tableOfContents} />
    </main>
  )
}
