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

export const revalidate = 3600;

const POSTS_PER_PAGE = 12;

const CATEGORY_META: Record<string, { title: string; description: string }> = {
  "client-guides": {
    title: "Client Guides",
    description: "Helpful guides for clients navigating adult services safely and respectfully.",
  },
  safety: {
    title: "Safety",
    description: "Essential safety tips and best practices for staying safe.",
  },
  "city-guides": {
    title: "City Guides",
    description: "Explore adult services and nightlife across cities worldwide.",
  },
  "service-explainers": {
    title: "Service Explainers",
    description: "Understand different types of adult services and what to expect.",
  },
  "industry-news": {
    title: "Industry News",
    description: "Latest news and updates from the adult services industry.",
  },
};

type Props = {
  params: Promise<{ category: string }>;
  searchParams: Promise<{ page?: string }>;
};

function categoryLabel(value: string) {
  const meta = CATEGORY_META[value];
  if (meta) return meta.title;
  return value.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}

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

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { category } = await params;
  const meta = CATEGORY_META[category];
  const title = meta ? meta.title : categoryLabel(category);
  const description = meta
    ? meta.description
    : `Browse ${title} articles on AdultWorld Blog.`;

  return {
    title: `${title} - AdultWorld Blog`,
    description,
    openGraph: {
      title: `${title} - AdultWorld Blog`,
      description,
      type: "website",
    },
  };
}

export default async function CategoryPage({ params, searchParams }: Props) {
  const { category } = await params;
  const sp = await searchParams;
  const page = Math.max(1, parseInt(sp.page || "1", 10));
  const title = categoryLabel(category);
  const meta = CATEGORY_META[category];

  const where = { published: true, category };

  const [posts, totalCount] = await Promise.all([
    prisma.blogPost.findMany({
      where,
      orderBy: { published_at: "desc" },
      skip: (page - 1) * POSTS_PER_PAGE,
      take: POSTS_PER_PAGE,
      select: {
        id: true,
        title: true,
        slug: true,
        excerpt: true,
        og_image: true,
        read_time: true,
        category: true,
        published_at: true,
        views: true,
      },
    }),
    prisma.blogPost.count({ where }),
  ]);

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

  return (
    <div className="max-w-6xl mx-auto space-y-8">
      {/* Header */}
      <div>
        <nav className="text-sm text-text-muted mb-4">
          <Link href="/blog-posts" className="hover:text-primary transition-colors">
            Blog
          </Link>
          <span className="mx-2">/</span>
          <span className="text-text">{title}</span>
        </nav>
        <h1 className="text-3xl font-bold">{title}</h1>
        {meta && <p className="text-text-muted mt-2">{meta.description}</p>}
      </div>

      {/* 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">
                  <span className="text-xs font-medium text-primary bg-primary/10 px-2 py-0.5 rounded-full">
                    {title}
                  </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 in this category yet</p>
          <Link href="/blog-posts" className="text-primary hover:underline mt-2 inline-block">
            View all articles
          </Link>
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          {page > 1 && (
            <Link
              href={`/blog-posts/category/${category}?page=${page - 1}`}
              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/category/${category}?page=${pageNum}`}
                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/category/${category}?page=${page + 1}`}
              className="bg-surface hover:bg-surface-light text-text px-4 py-2 rounded-lg transition-colors"
            >
              Next
            </Link>
          )}
        </div>
      )}
    </div>
  );
}
