import { useState, useEffect } from "react";
import { useBlogCategories } from "@/lib/hooks/useBlog";

const PostFilterButtons = ({ handleClick, active }: any) => {
  const { categories: apiCategories, loading, error } = useBlogCategories();
  const [categories, setCategories] = useState<any[]>([]);

  useEffect(() => {
    if (!loading && apiCategories.length > 0) {
      // Add "All" category at the beginning
      const allCategory = {
        id: 0,
        title: "All",
        slug: "all",
        display_order: 0
      };
      setCategories([allCategory, ...apiCategories]);
    }
  }, [apiCategories, loading]);

  if (loading) {
    return (
      <div className="row">
        <div className="col-12">
          <div className="post-filter__wrapper mt-80">
            <p>Loading categories...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    // Fallback to showing "All" button only
    return (
      <div className="row">
        <div className="col-12">
          <div className="post-filter__wrapper mt-80">
            <button
              aria-label="Filter Post"
              className="active"
              onClick={() => handleClick("all")}
            >
              All
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="row">
      <div className="col-12">
        <div className="post-filter__wrapper mt-80">
          {categories.map((item) => {
            return (
              <button
                aria-label="Filter Post"
                key={item.id}
                className={active === item.slug ? " active" : ""}
                onClick={() => handleClick(item.slug)}
              >
                {item.title}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default PostFilterButtons;
