"use client";
import httpClient from "@/request/api";
import { endPoints } from "@/request/links";
import { useQuery } from "@tanstack/react-query";
import ProductCard from "./productCard";
import { useCategory } from "@/store/useCategory";

export default function MainProduct() {
  const category = useCategory((state) => state.category);

  const requestLink = category.have_sub_category
    ? endPoints.subCategory.byId(category.id)
    : endPoints.product.byCategory(category.id || 0);

  const { data, isLoading, error } = useQuery({
    queryKey: ["products", category.id],
    queryFn: () => httpClient(requestLink),
    select: (data) => data?.data?.data?.results,
  });

  if (isLoading) {
    return (
      <div className="grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-5">
        {[1, 2, 3].map((i) => (
          <div key={i} className="h-96 bg-gray-800 animate-pulse rounded-2xl" />
        ))}
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center text-red-500 py-10">
        Ma'lumotlarni yuklashda xatolik yuz berdi
      </div>
    );
  }

  if (!data || data.length === 0) {
    return (
      <div className="text-center text-gray-400 py-10">
        Mahsulotlar topilmadi
      </div>
    );
  }

  return (
    <div className="grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-5">
      {data.map((item: any) => (
        <ProductCard
          key={item.id} // ✅ index o'rniga id ishlatish
          title={item.name}
          image={item.image}
          slug={item.slug}
        />
      ))}
    </div>
  );
}
