"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";

export default function SubcategoryList({ params }) {
  console.log(params);
  console.log(params.id);
  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 category details
        const categoryResponse = await axios.get(
          `${backendUrl}/products/category/`
        );
        const selectedCategory = categoryResponse.data.find(
          (cat) => cat.id == params.id
        );
        setCategory(selectedCategory);

        // Fetch subcategories for this category
        const subcategoriesResponse = await axios.get(
          `${backendUrl}/admins/product/subcategories/?category_id=${params.id}`
        );
        setSubcategories(subcategoriesResponse.data);
        console.log("Selected sub category")
        console.log(subcategoriesResponse.data);
        // console.log(sub)
      } catch (err) {
        console.error("Error fetching data:", err);
        setError("Failed to load subcategories. Please try again later.");
      } finally {
        setLoading(false);
      }
    };

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

  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.id}/subcategory/${subcategory.id}`}>
                  <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>
  );
}
