"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";
import { useFilter } from "@/lib/filter-zustand";
import { useEffect, useMemo } from "react";
import { useProductPageInfo } from "@/store/useProduct";
import { useSubCategory } from "@/store/useSubCategory";

export default function MainProduct() {
  const category = useCategory((state) => state.category);
  const subCategory = useSubCategory((state) => state.subCategory);
  const filter = useFilter((state) => state.filter);
  const getFiltersByType = useFilter((state) => state.getFiltersByType);
  const setProduct = useProductPageInfo((state) => state.setProducts);

  // Query params yaratish
  const queryParams = useMemo(() => {
    const catalog = getFiltersByType("catalog");
    const size = getFiltersByType("size");

    // Har bir filter uchun query string yaratish
    const catalogParams = catalog.map((item) => `catalog=${item.id}`).join("&");
    const sizeParams = size.map((item) => `size=${item.id}`).join("&");

    // Barcha paramslarni birlashtirish
    const allParams = [catalogParams, sizeParams].filter(Boolean).join("&");

    return allParams ? `&${allParams}` : "";
  }, [filter, getFiltersByType]);

  // Request link yaratish
  const requestLink = useMemo(() => {
    const baseLink = category.have_sub_category
      ? endPoints.product.bySubCategory(subCategory.id)
      : endPoints.product.byCategory(category.id || 0);

    // Query params qo'shish
    return `${baseLink}${queryParams}`;
  }, [category.id, category.have_sub_category, queryParams]);

  const { data, isLoading, error } = useQuery({
    queryKey: ["products", subCategory.id, queryParams],
    queryFn: () => httpClient(requestLink),
    select: (data) => {
      console.log("product: ", data?.data?.data?.results);
      return 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
          getProduct={() => setProduct(item)}
          title={item.name}
          image={item?.images[0]?.image ||''}
          slug='special_product'
        />
      ))}
    </div>
  );
}
