import prisma from "@/lib/prisma";
import Link from "next/link";
import Image from "next/image";
import type { Metadata } from "next";

export const revalidate = 300; // ISR (Stage 4): was force-dynamic

const POSTS_PER_PAGE = 12;

const CATEGORIES = [
  { label: "All", value: "" },
  { label: "Client Guides", value: "client-guides" },
  { label: "Safety", value: "safety" },
  { label: "City Guides", value: "city-guides" },
  { label: "Service Explainers", value: "service-explainers" },
  { label: "Industry News", value: "industry-news" },
];

export async function generateMetadata(): Promise<Metadata> {
  return {
    title: "Blog - AdultWorld",
    description:
      "Read the latest guides, safety tips, city guides, and industry news on AdultWorld. Stay informed with expert articles and insights.",
    alternates: {
      canonical: "/blog-posts",
    },
    openGraph: {
      title: "Blog - AdultWorld",
      description:
        "Read the latest guides, safety tips, city guides, and industry news on AdultWorld.",
      type: "website",
    },
  };
}

function formatDate(date: Date | null) {
  if (!date) return "";
  return new Intl.DateTimeFormat(undefined, {
    day: "numeric",
    month: "short",
    year: "numeric",
  }).format(new Date(date));
}

function categoryLabel(value: string | null) {
  if (!value) return null;
  const cat = CATEGORIES.find((c) => c.value === value);
  return cat ? cat.label : value.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}

export default async function BlogIndexPage({
  searchParams,
}: {
  searchParams: Promise<{ page?: string; category?: string; q?: string }>;
}) {
  const params = await searchParams;
  const page = Math.max(1, parseInt(params.page || "1", 10));
  const category = params.category || "";
  const query = params.q || "";

  const where = {
    published: true,
    ...(category ? { category } : {}),
    ...(query ? { title: { contains: query } } : {}),
  };

  // Card grid only renders title/slug/excerpt/og_image/read_time —
  // explicit select avoids fetching the full body @db.Text per row.
  const cardSelect = {
    id: true,
    title: true,
    slug: true,
    excerpt: true,
    og_image: true,
    read_time: true,
    category: true,
    published_at: true,
    views: true,
  } as const;

  const [posts, totalCount, featuredPost] = await Promise.all([
    prisma.blogPost.findMany({
      where,
      orderBy: { published_at: "desc" },
      skip: (page - 1) * POSTS_PER_PAGE,
      take: POSTS_PER_PAGE,
      select: cardSelect,
    }),
    prisma.blogPost.count({ where }),
    page === 1 && !category && !query
      ? prisma.blogPost.findFirst({
          where: { published: true, featured: true },
          orderBy: { published_at: "desc" },
          select: cardSelect,
        })
      : null,
  ]);

  const totalPages = Math.ceil(totalCount / POSTS_PER_PAGE);

  return (
    <div className="max-w-6xl mx-auto space-y-8">
      {/* Header */}
      <div className="space-y-4">
        <h1 className="text-3xl font-bold">Blog</h1>
        <p className="text-text-muted">
          Expert guides, city recommendations, safety advice, and industry insights for escorts and clients. Updated regularly with new articles.
        </p>
      </div>

      {/* Search Bar */}
      <form method="GET" className="flex gap-2">
        <input
          type="text"
          name="q"
          defaultValue={query}
          placeholder="Search articles..."
          className="flex-1 bg-surface border border-surface-light rounded-lg px-4 py-2 text-text placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-primary"
        />
        {category && <input type="hidden" name="category" value={category} />}
        <button
          type="submit"
          className="bg-primary hover:bg-primary-dark text-white px-6 py-2 rounded-lg font-medium transition-colors"
        >
          Search
        </button>
      </form>

      {/* Category Tabs */}
      <div className="flex flex-wrap gap-2">
        {CATEGORIES.map((cat) => {
          const isActive = category === cat.value;
          const href = cat.value
            ? `/blog-posts?category=${cat.value}${query ? `&q=${query}` : ""}`
            : `/blog-posts${query ? `?q=${query}` : ""}`;
          return (
            <Link
              key={cat.value}
              href={href}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                isActive
                  ? "bg-primary text-white"
                  : "bg-surface hover:bg-surface-light text-text-muted hover:text-text"
              }`}
            >
              {cat.label}
            </Link>
          );
        })}
      </div>

      {/* Featured Post Hero */}
      {featuredPost && (
        <Link
          href={`/blog-posts/${featuredPost.slug}`}
          className="block bg-surface rounded-lg overflow-hidden hover:ring-1 hover:ring-primary transition-all group"
        >
          {featuredPost.og_image && (
            <div className="relative h-64 md:h-80 overflow-hidden">
              <Image
                src={featuredPost.og_image}
                alt={featuredPost.title}
                fill
                sizes="(max-width:768px) 100vw, 90vw"
                className="object-cover group-hover:scale-105 transition-transform duration-300"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent" />
              <div className="absolute bottom-0 left-0 right-0 p-6">
                <span className="inline-block bg-primary text-white text-xs font-semibold px-3 py-1 rounded-full mb-3">
                  Featured
                </span>
                <h2 className="text-2xl md:text-3xl font-bold text-white mb-2">
                  {featuredPost.title}
                </h2>
                {featuredPost.excerpt && (
                  <p className="text-gray-200 line-clamp-2">{featuredPost.excerpt}</p>
                )}
              </div>
            </div>
          )}
          {!featuredPost.og_image && (
            <div className="p-6">
              <span className="inline-block bg-primary text-white text-xs font-semibold px-3 py-1 rounded-full mb-3">
                Featured
              </span>
              <h2 className="text-2xl font-bold mb-2 group-hover:text-primary transition-colors">
                {featuredPost.title}
              </h2>
              {featuredPost.excerpt && (
                <p className="text-text-muted line-clamp-2">{featuredPost.excerpt}</p>
              )}
            </div>
          )}
        </Link>
      )}

      {/* Posts Grid */}
      {posts.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {posts.map((post) => (
            <Link
              key={post.id}
              href={`/blog-posts/${post.slug}`}
              className="bg-surface rounded-lg overflow-hidden hover:ring-1 hover:ring-primary transition-all group flex flex-col"
            >
              {post.og_image && (
                <div className="h-44 overflow-hidden relative">
                  <Image
                    src={post.og_image}
                    alt={post.title}
                    fill
                    sizes="(max-width:768px) 100vw, (max-width:1024px) 50vw, 33vw"
                    className="object-cover group-hover:scale-105 transition-transform duration-300"
                  />
                </div>
              )}
              <div className="p-4 flex flex-col flex-1">
                <div className="flex items-center gap-2 mb-2">
                  {post.category && (
                    <span className="text-xs font-medium text-primary bg-primary/10 px-2 py-0.5 rounded-full">
                      {categoryLabel(post.category)}
                    </span>
                  )}
                  <span className="text-xs text-text-muted">{post.read_time} min read</span>
                </div>
                <h3 className="font-semibold text-lg mb-2 group-hover:text-primary transition-colors line-clamp-2">
                  {post.title}
                </h3>
                {post.excerpt && (
                  <p className="text-text-muted text-sm line-clamp-3 mb-4">{post.excerpt}</p>
                )}
                <div className="mt-auto flex items-center justify-between text-xs text-text-muted">
                  <span>{formatDate(post.published_at)}</span>
                  <span>{post.views.toLocaleString()} views</span>
                </div>
              </div>
            </Link>
          ))}
        </div>
      ) : (
        <div className="text-center py-16 text-text-muted">
          <p className="text-lg">No articles found</p>
          {(query || category) && (
            <Link href="/blog-posts" className="text-primary hover:underline mt-2 inline-block">
              Clear filters
            </Link>
          )}
        </div>
      )}

      {/* Result count + Load More */}
      {totalCount > 0 && (
        <div className="text-center space-y-3">
          <p className="text-sm text-text-muted">
            Showing {Math.min(page * POSTS_PER_PAGE, totalCount)} of {totalCount} articles
          </p>
          {page < totalPages && (
            <Link
              href={`/blog-posts?page=${page + 1}${category ? `&category=${category}` : ""}${query ? `&q=${query}` : ""}`}
              className="inline-block bg-primary hover:bg-primary-dark text-white px-8 py-3 rounded-lg font-medium transition-colors"
            >
              Load More Articles
            </Link>
          )}
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          {page > 1 && (
            <Link
              href={`/blog-posts?page=${page - 1}${category ? `&category=${category}` : ""}${query ? `&q=${query}` : ""}`}
              className="bg-surface hover:bg-surface-light text-text px-4 py-2 rounded-lg transition-colors"
            >
              Previous
            </Link>
          )}
          {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
            let pageNum: number;
            if (totalPages <= 7) {
              pageNum = i + 1;
            } else if (page <= 4) {
              pageNum = i + 1;
            } else if (page >= totalPages - 3) {
              pageNum = totalPages - 6 + i;
            } else {
              pageNum = page - 3 + i;
            }
            return (
              <Link
                key={pageNum}
                href={`/blog-posts?page=${pageNum}${category ? `&category=${category}` : ""}${query ? `&q=${query}` : ""}`}
                className={`px-4 py-2 rounded-lg transition-colors ${
                  pageNum === page
                    ? "bg-primary text-white"
                    : "bg-surface hover:bg-surface-light text-text-muted"
                }`}
              >
                {pageNum}
              </Link>
            );
          })}
          {page < totalPages && (
            <Link
              href={`/blog-posts?page=${page + 1}${category ? `&category=${category}` : ""}${query ? `&q=${query}` : ""}`}
              className="bg-surface hover:bg-surface-light text-text px-4 py-2 rounded-lg transition-colors"
            >
              Next
            </Link>
          )}
        </div>
      )}
    </div>
  );
}
