"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Search } from "lucide-react";
import BlogCard from "./blog-card";
import { Pagination } from "@/components/ui/pagination";
import { FadeIn } from "../ui/fade-in";
import type { WebsiteBlogListItem } from "@/lib/api/website/blog-types";

const ITEMS_PER_PAGE = 9;

type Blog = {
  slug: string;
  title: string;
  description: string;
  image?: string;
  imageAlt: string;
};

type BlogsContentProps = {
  blogs?: WebsiteBlogListItem[];
};

export default function BlogsContent({ blogs: apiBlogs }: BlogsContentProps) {
  const t = useTranslations("blogsPage");
  const tPagination = useTranslations("ourWorks.pagination");
  const [currentPage, setCurrentPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState("");

  const blogs: Blog[] = (apiBlogs ?? []).map((blog) => ({
    slug: blog.slug,
    title: blog.title,
    description: blog.description ?? "",
    image: blog.imageSrc,
    imageAlt: blog.imageAlt ?? blog.title,
  }));
  const normalizedSearchQuery = searchQuery.trim().toLowerCase();

  const filteredBlogs = blogs.filter(
    (blog) =>
      blog.title.toLowerCase().includes(normalizedSearchQuery) ||
      blog.description.toLowerCase().includes(normalizedSearchQuery)
  );

  const totalPages = Math.ceil(filteredBlogs.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex = startIndex + ITEMS_PER_PAGE;
  const currentBlogs = filteredBlogs.slice(startIndex, endIndex);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    // Scroll to top of content
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <section className="w-full bg-white px-4 pt-12 pb-20 sm:px-6 sm:pt-14 sm:pb-24 md:px-8 md:pt-16 md:pb-28 lg:px-12 lg:pb-32 xl:px-[120px]">
      <div className="mx-auto flex w-full max-w-[1200px] flex-col gap-6 sm:gap-8 md:gap-10">
        <div className="relative mx-auto w-full max-w-[720px]">
          <input
            type="text"
            placeholder={t("searchPlaceholder")}
            value={searchQuery}
            onChange={(e) => {
              setSearchQuery(e.target.value);
              setCurrentPage(1); // Reset to first page on search
            }}
            className="w-full h-14 px-4 pe-12 bg-muted border border-border rounded-[12px] text-[14px] text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
          />
          <Search className="absolute end-4 top-1/2 -translate-y-1/2 size-6 text-muted-foreground" />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 w-full">
          {currentBlogs.map((blog, index) => (
            <FadeIn key={blog.slug} delay={0.2 * index}>
              <BlogCard
                slug={blog.slug}
                title={blog.title}
                description={blog.description}
                image={blog.image}
                imageAlt={blog.imageAlt}
              />
            </FadeIn>
          ))}
        </div>

        {totalPages > 1 && (
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            totalItems={filteredBlogs.length}
            itemsPerPage={ITEMS_PER_PAGE}
            onPageChange={handlePageChange}
            showItemsPerPage={false}
            className="justify-center border-t-0 px-0 py-0 [&>div:first-child]:hidden [&>div:last-child]:hidden"
            labels={{
              previous: tPagination("previous"),
              next: tPagination("next"),
              showing: tPagination("showing"),
              of: tPagination("of"),
              itemsPerPage: tPagination("itemsPerPage"),
            }}
          />
        )}
      </div>
    </section>
  );
}
