"use client";

import Link from "next/link";
import React, { useState, useEffect } from "react";
import { backendUrl } from "@/utils/axios";
import axios from "axios";
import Image from "next/image";
import slugify from "slugify";

export default function SubcategoryList({ params }) {
  //console.log("category params is", params);
  //console.log("Category name:", params.name);

  const [subcategories, setSubcategories] = useState([]);
  const [category, setCategory] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch all categories
        const categoryResponse = await axios.get(`${backendUrl}/products/category/`);

        // Find the category by name
        const selectedCategory = categoryResponse.data.find(
          (cat) => cat.category_name.toLowerCase() === decodeURIComponent(params.name).toLowerCase()
        );

        if (!selectedCategory) {
          setError("Category not found.");
          setLoading(false);
          return;
        }

        setCategory(selectedCategory);

        // Fetch subcategories using category id
        const subcategoriesResponse = await axios.get(
          `${backendUrl}/admins/product/subcategories/?category_id=${selectedCategory.id}`
        );
        setSubcategories(subcategoriesResponse.data);

        console.log("Selected subcategories", subcategoriesResponse.data);
      } catch (err) {
        console.error("Error fetching data:", err);
        setError("Failed to load subcategories. Please try again later.");
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [params.name]);

  if (loading) {
    return <div className="py-16 text-center">Loading subcategories...</div>;
  }

  if (error) {
    return <div className="py-16 text-center text-red-500">{error}</div>;
  }

  return (
    <section className="py-16 bg-gray-50">
      <div className="container mx-auto px-4">
        <h2 className="text-4xl font-bold text-center text-gray-800 mb-12">
          Explore {category ? category.category_name : "Category"} Subcategories
        </h2>

        {subcategories.length === 0 ? (
          <p className="text-center text-lg">
            No subcategories available for this category.
          </p>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8">
            {subcategories.map((subcategory) => (
              <div
                key={subcategory.id}
                className="bg-white shadow-lg rounded-lg overflow-hidden transition-transform transform hover:scale-105"
              >
                <Link href={`/category/${params.name}/subcategory/${slugify(subcategory.subcategory_name, { lower: true })}`}>
                  <div className="relative w-full h-64 bg-gray-200">
                    <Image
                      src={`${
                        subcategory?.image
                          ? subcategory.image.startsWith("http")
                            ? subcategory.image
                            : `${backendUrl}/media${
                                subcategory.image.startsWith("/") ? "" : "/"
                              }${subcategory.image}`
                          : "/default-subcategory.jpg"
                      }`}
                      alt={subcategory.subcategory_name}
                      layout="fill"
                      objectFit="cover"
                      className="rounded-t-lg"
                    />
                  </div>
                  <div className="p-5">
                    <h3 className="text-lg font-semibold text-gray-900 mb-2 truncate">
                      {subcategory.subcategory_name}
                    </h3>
                    <p className="text-sm text-gray-600">
                      Click to view collections
                    </p>
                  </div>
                </Link>
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}