"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { searchListing, categoryApiCall } from "../../../../api/api";
import { RootState } from "../../../../store";
import Image from "next/image";

interface Category {
  name: string;
  icon: string;
  id: number;
}

function CategorySlider() {
  const router = useRouter();
  const dispatch = useDispatch<any>();

  const [showAll, setShowAll] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [windowWidth, setWindowWidth] = useState(
    typeof window !== "undefined" ? window.innerWidth : 1024
  );

  const { categories } = useSelector(
    (state: RootState) => state.CategoryListing
  );

  useEffect(() => {
    dispatch(categoryApiCall());
  }, [dispatch]);

  useEffect(() => {
    if (typeof window === "undefined") return;

    const handleResize = () => setWindowWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const handleCategoryClick = async (id: number, name: string) => {
    setSelectedCategory(id);

    if (!id) return;

    const categoryName = name
      .replace(/[^a-zA-Z0-9\s]/g, "")
      .replace(/\s+/g, "-")
      .toLowerCase();

    try {
      await dispatch(searchListing({ keyword: "", category_id: id })).unwrap();
      router.push(`/${id}/${categoryName}`);
    } catch (err) {
      console.error("Search failed:", err);
    }
  };

  // Show a limited number of categories based on screen size
  let visibleCategories = categories?.data || [];

  if (!showAll) {
    if (windowWidth < 480) {
      visibleCategories = categories?.data?.slice(0, 4) || [];
    } else if (windowWidth < 1025) {
      visibleCategories = categories?.data?.slice(0, 3) || [];
    }
  }

  return (
    <div className="mx-auto px-4 sm:px-6 lg:max-w-4xl lg:px-8 font-system font-bold text-black mt-6 block lg:hidden">
      <h2 className="text-center text-xl md:text-2xl mb-4">Categories</h2>

      <div className="grid grid-cols-2 xsm:grid-cols-3 gap-4">
        {visibleCategories.map((category: Category) => (
          <div
            key={category.id}
            className={`p-4 flex flex-col items-center justify-center border rounded-lg cursor-pointer transition-all ${
              selectedCategory === category.id
                ? "bg-yellow-400 text-white"
                : "bg-white border-gray-300"
            }`}
            onClick={() => handleCategoryClick(category.id, category.name)}
          >
            <div className="w-16 h-16 flex items-center justify-center">
              <Image
                unoptimized
                src={category.icon}
                alt={category.name}
                width={64}
                height={64}
                className="w-full h-full object-contain"
              />
            </div>
            <p className="mt-2 text-center text-sm font-semibold">
              {category.name}
            </p>
          </div>
        ))}
      </div>

      {/* Show All Button */}
      {!showAll ? (
        categories?.data?.length > visibleCategories.length &&
        windowWidth < 1025 && (
          <div className="mt-6 flex justify-center">
            <button
              className="bg-yellow-400 text-black font-bold py-2 px-6 rounded-full"
              onClick={() => setShowAll(true)}
            >
              Show All
            </button>
          </div>
        )
      ) : (
        <div className="mt-6 flex justify-center">
          <button
            className="bg-yellow-400 text-black font-bold py-2 px-6 rounded-full"
            onClick={() => setShowAll(false)}
          >
            Show Less
          </button>
        </div>
      )}
    </div>
  );
}

export default CategorySlider;
