"use client";

import { useMemo, useState } from "react";
import { Search } from "lucide-react";

import BlogGrid from "@/components/blogs/BlogGrid";
import type { BlogPageCopy, BlogPost } from "@/data/blogs.data";
import type { Locale } from "@/lib/locales";

export default function BlogExplorer({ categories, copy, locale, posts }: { categories: string[]; copy: BlogPageCopy; locale: Locale; posts: BlogPost[] }) {
  const [activeCategory, setActiveCategory] = useState(copy.all);
  const [query, setQuery] = useState("");
  const filteredPosts = useMemo(() => {
    const normalizedQuery = query.trim().toLocaleLowerCase();
    return posts.filter((post) => {
      const matchesCategory = activeCategory === copy.all || post.category === activeCategory;
      const matchesSearch = !normalizedQuery || `${post.title} ${post.excerpt} ${post.category}`.toLocaleLowerCase().includes(normalizedQuery);
      return matchesCategory && matchesSearch;
    });
  }, [activeCategory, copy.all, posts, query]);

  return (
    <section className="mx-auto max-w-[1360px] px-6 pb-14 xl:px-8">
      <div className="flex flex-col justify-between gap-4 lg:flex-row lg:items-end">
        <div>
          <h2 className="text-3xl font-extrabold tracking-[-0.05em] text-[#172142]">{copy.latestTitle}</h2>
          <p className="mt-2 max-w-[680px] text-[14px] leading-6 text-[#748099]">{copy.latestDescription}</p>
        </div>
        <label className="flex h-11 min-w-[260px] items-center gap-2 rounded-xl border border-[#e1e6f1] bg-white px-3 text-[#8a96aa] shadow-sm">
          <Search size={17} />
          <span className="sr-only">{copy.searchPlaceholder}</span>
          <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder={copy.searchPlaceholder} className="min-w-0 flex-1 bg-transparent text-[13px] text-[#34405d] outline-none placeholder:text-[#a3adbc]" />
        </label>
      </div>
      <div className="mt-5 flex flex-wrap gap-2">
        {[copy.all, ...categories].map((category) => <button key={category} type="button" onClick={() => setActiveCategory(category)} className={`rounded-full border px-3.5 py-2 text-[11px] font-bold transition ${activeCategory === category ? "border-[#5e68e7] bg-[#5e68e7] text-white shadow-md" : "border-[#e1e6f1] bg-white text-[#6e7a94] hover:border-[#bdc5ff] hover:text-[#5964dc]"}`}>{category}</button>)}
      </div>
      <div className="mt-7">
        <BlogGrid locale={locale} posts={filteredPosts} readMore={copy.readMore} />
        {filteredPosts.length === 0 ? <p className="rounded-2xl border border-[#e5eaf4] bg-white p-8 text-center text-[13px] text-[#748099]">{copy.searchPlaceholder}: 0</p> : null}
      </div>
    </section>
  );
}
