"use client";

import Link from "next/link";
import { useState, useMemo } from "react";
import { Container } from "@/components/container";
import { Breadcrumbs } from "@/components/breadcrumbs";
import { BlogPost } from "@/content/blog";
import { BlogCard } from "./blog-card";
import { ChevronLeft, ChevronRight, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils";
import {
  BLOG_CATEGORIES_LIST,
  type CategoryInfo,
} from "@/lib/blog-categories-data";

interface BlogCategoryViewProps {
  categoryInfo: CategoryInfo;
  posts: BlogPost[];
}

export function BlogCategoryView({ categoryInfo, posts }: BlogCategoryViewProps) {
  const [currentPage, setCurrentPage] = useState<number>(1);
  const POSTS_PER_PAGE = 6;

  // Filter posts matching this category
  const categoryPosts = useMemo(() => {
    return posts.filter(
      (p) => p.category.toLowerCase() === categoryInfo.name.toLowerCase()
    );
  }, [posts, categoryInfo]);

  const totalPages = Math.ceil(categoryPosts.length / POSTS_PER_PAGE) || 1;
  const paginatedPosts = useMemo(() => {
    const startIndex = (currentPage - 1) * POSTS_PER_PAGE;
    return categoryPosts.slice(startIndex, startIndex + POSTS_PER_PAGE);
  }, [categoryPosts, currentPage]);

  return (
    <div className="page-top-space pb-12 md:pb-20">
      <Container className="mx-auto w-full max-w-6xl px-5 md:px-8">
        <Breadcrumbs
          items={[
            { label: "Blog", href: "/blog" },
            { label: categoryInfo.title },
          ]}
          className="mb-8"
        />

        {/* Category Pills Strip */}
        <div className="flex flex-wrap items-center gap-2">
          {BLOG_CATEGORIES_LIST.map((cat) => {
            const isActive = cat.slug === categoryInfo.slug;
            return (
              <Link
                key={cat.slug}
                href={`/blog/category/${cat.slug}`}
                aria-current={isActive ? "page" : undefined}
                className={cn(
                  "inline-flex items-center rounded-lg px-3.5 py-1.5 text-xs font-semibold tracking-wider uppercase transition-all",
                  isActive
                    ? "bg-primary text-primary-foreground shadow-xs"
                    : "border border-border/80 bg-card text-muted-foreground hover:border-foreground/40 hover:text-foreground"
                )}
              >
                {cat.name}
              </Link>
            );
          })}
        </div>

        {/* Header Section */}
        <div className="mt-8 max-w-3xl">
          <h1 className="font-display text-3xl font-bold tracking-tight text-foreground md:text-5xl md:leading-tight">
            {categoryInfo.title}
          </h1>
          <p className="mt-4 text-base leading-relaxed text-muted-foreground md:text-lg">
            {categoryInfo.description}
          </p>
        </div>

        {/* Posts Grid */}
        <div className="mt-12">
          {paginatedPosts.length > 0 ? (
            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {paginatedPosts.map((post) => (
                <BlogCard key={post.slug} post={post} />
              ))}
            </div>
          ) : (
            <div className="rounded-2xl border border-dashed border-border p-12 text-center">
              <p className="text-base text-muted-foreground">
                No articles published in this category yet.
              </p>
              <Link
                href="/blog"
                className="mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-primary hover:underline"
              >
                <span>View all articles in the Blog</span>
                <ArrowRight className="size-4" />
              </Link>
            </div>
          )}
        </div>

        {/* Pagination Controls */}
        {totalPages > 1 && (
          <div className="mt-12 flex flex-wrap items-center justify-center gap-2">
            <button
              onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
              disabled={currentPage === 1}
              className="flex size-9 items-center justify-center rounded-lg border border-border bg-card text-muted-foreground transition hover:border-foreground/40 hover:text-foreground disabled:pointer-events-none disabled:opacity-40"
              aria-label="Previous page"
            >
              <ChevronLeft className="size-4" />
            </button>
            {Array.from({ length: totalPages }).map((_, idx) => (
              <button
                key={idx}
                onClick={() => setCurrentPage(idx + 1)}
                aria-current={currentPage === idx + 1 ? "page" : undefined}
                className={cn(
                  "flex size-9 items-center justify-center rounded-lg text-xs font-semibold transition",
                  currentPage === idx + 1
                    ? "bg-primary text-primary-foreground"
                    : "border border-border bg-card text-muted-foreground hover:border-foreground/40 hover:text-foreground"
                )}
              >
                {idx + 1}
              </button>
            ))}
            <button
              onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
              disabled={currentPage === totalPages}
              className="flex size-9 items-center justify-center rounded-lg border border-border bg-card text-muted-foreground transition hover:border-foreground/40 hover:text-foreground disabled:pointer-events-none disabled:opacity-40"
              aria-label="Next page"
            >
              <ChevronRight className="size-4" />
            </button>
          </div>
        )}
      </Container>
    </div>
  );
}
