import { db } from "@/lib/db";
import { blogPosts, blogLikes, users } from "@/lib/db/schema";
import { eq, and, sql } from "drizzle-orm";
import { notFound } from "next/navigation";
import Link from "next/link";
import { formatCount } from "@/lib/formatCount";
import { auth } from "@/lib/auth";
import { getSetting } from "@/lib/settings";
import BlogLikeButton from "@/components/BlogLikeButton";
import BlogComments from "@/components/BlogComments";
import TrackLastRead from "@/components/TrackLastRead";
import { getCategoriesForPosts } from "@/lib/blogCategories";
import PartnersInMission from "@/components/PartnersInMission";
import type { Metadata } from "next";

export const dynamic = "force-dynamic";

async function getPost(slug: string) {
  return (await db.select().from(blogPosts).where(eq(blogPosts.slug, slug)))[0];
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post || post.status !== "published") return {};

  const appUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
  const title = post.metaTitle || post.title;
  const description = post.metaDescription || post.excerpt || undefined;
  const url = `${appUrl}/blog/${post.slug}`;

  return {
    title,
    description,
    alternates: { canonical: url },
    openGraph: {
      title,
      description,
      url,
      type: "article",
      publishedTime: post.publishedAt ? new Date(post.publishedAt).toISOString() : undefined,
      images: post.featuredImageUrl ? [{ url: post.featuredImageUrl }] : undefined,
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: post.featuredImageUrl ? [post.featuredImageUrl] : undefined,
    },
  };
}

export default async function BlogPostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post || post.status !== "published") return notFound();

  // Fire-and-forget view count increment — doesn't block the page render.
  db.update(blogPosts).set({ viewCount: sql`${blogPosts.viewCount} + 1` }).where(eq(blogPosts.id, post.id)).catch(() => {});

  const author = (await db.select().from(users).where(eq(users.id, post.authorId)))[0];
  const siteName = await getSetting("siteName", "GraceMembership");
  const appUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";

  const session = await auth();
  let initiallyLiked = false;
  if (session?.user) {
    const userId = (session.user as any).id;
    initiallyLiked = !!(await db.select().from(blogLikes).where(and(eq(blogLikes.postId, post.id), eq(blogLikes.userId, userId))))[0];
  }

  const gallery: string[] = post.galleryImages ? JSON.parse(post.galleryImages) : [];
  const postCategories = (await getCategoriesForPosts([post.id]))[post.id] || [];

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Article",
    headline: post.title,
    description: post.metaDescription || post.excerpt || undefined,
    image: post.featuredImageUrl || undefined,
    datePublished: post.publishedAt ? new Date(post.publishedAt).toISOString() : undefined,
    dateModified: post.updatedAt ? new Date(post.updatedAt).toISOString() : undefined,
    author: { "@type": "Person", name: author?.name || siteName },
    publisher: { "@type": "Organization", name: siteName },
    mainEntityOfPage: `${appUrl}/blog/${post.slug}`,
  };

  return (
    <div className="max-w-6xl mx-auto">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
      <TrackLastRead slug={post.slug} />

      <div className="flex flex-col xl:flex-row gap-8 items-start">
        {/* ── Main article column ── */}
        <article className="flex-1 min-w-0 max-w-3xl">

          <div className="flex items-center justify-between mb-4">
            <Link href="/blog" className="text-red-500 text-sm">← Back to blog</Link>
            <Link
              href="/tips"
              className="flex items-center gap-1.5 bg-red-600 hover:bg-red-700 text-white text-xs font-semibold px-3 py-1.5 rounded-full transition-colors xl:hidden"
            >
              💝 Support
            </Link>
          </div>

          {post.featuredImageUrl && (
            <img src={post.featuredImageUrl} className="w-full aspect-video object-cover rounded-xl mb-6" alt={post.title} />
          )}

          <h1 className="text-3xl font-bold mb-2">{post.title}</h1>
          <div className="flex items-center gap-2 text-sm text-neutral-500 mb-3">
            <span>{author?.name || "Admin"}</span>
            <span>·</span>
            <span>{post.publishedAt ? new Date(post.publishedAt).toLocaleDateString() : ""}</span>
            <span>·</span>
            <span>👁 {formatCount(post.viewCount + 1)} views</span>
          </div>
          {postCategories.length > 0 && (
            <div className="flex flex-wrap gap-1.5 mb-6">
              {postCategories.map((c) => (
                <Link key={c.slug} href={`/blog?category=${c.slug}`} className="text-xs bg-neutral-800 hover:bg-neutral-700 text-neutral-300 px-2.5 py-1 rounded-full transition-colors">
                  {c.name}
                </Link>
              ))}
            </div>
          )}

          <div
            className="prose-content text-neutral-200 leading-relaxed mb-6 [&_h2]:text-xl [&_h2]:font-bold [&_h2]:mt-6 [&_h2]:mb-3 [&_h3]:text-lg [&_h3]:font-bold [&_h3]:mt-5 [&_h3]:mb-2 [&_blockquote]:border-l-4 [&_blockquote]:border-red-600 [&_blockquote]:pl-4 [&_blockquote]:italic [&_blockquote]:text-neutral-400 [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_a]:text-red-500 [&_a]:underline [&_p]:mb-4 [&_img]:rounded-lg [&_img]:my-4"
            dangerouslySetInnerHTML={{ __html: post.contentHtml }}
          />

          {gallery.length > 0 && (
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 mb-6">
              {gallery.map((url) => (
                <img key={url} src={url} className="w-full aspect-square object-cover rounded-lg" alt="" />
              ))}
            </div>
          )}

          <div className="flex items-center py-4 border-y border-neutral-800 mb-8">
            <BlogLikeButton slug={post.slug} initialLiked={initiallyLiked} initialCount={post.likeCount} />
          </div>

          <BlogComments slug={post.slug} />
        </article>

        {/* ── Right sidebar: sticky supporters scroll tab ── */}
        <aside className="hidden xl:block w-72 shrink-0 sticky top-20 self-start">
          <div className="card p-4">
            <div className="flex items-center justify-between mb-3">
              <h3 className="font-bold text-sm">Our Supporters</h3>
              <Link href="/tips" className="text-xs bg-red-600 hover:bg-red-700 text-white px-2.5 py-1 rounded-full transition-colors">
                💝 Support
              </Link>
            </div>
            <p className="text-xs text-neutral-500 mb-3">These people make this content possible</p>
            <PartnersInMission />
          </div>
        </aside>
      </div>
    </div>
  );
}
