"use client";

import httpClient from "@/request/api";
import { endPoints } from "@/request/links";
import { useQuery } from "@tanstack/react-query";
import { useCategory } from "@/store/useCategory";
import Card from "./card";
import { useTranslations } from "next-intl";

export function MainSubCategory() {
  const category = useCategory((state) => state.category);
  const t = useTranslations();
  const { data, isLoading, error } = useQuery({
    queryKey: ["subCategory"],
    queryFn: () => httpClient(endPoints.subCategory.byId(category.id)),
    select: (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">
        {t("loading_error")}
      </div>
    );
  }

  if (!data || data.length === 0) {
    return (
      <div className="text-center text-gray-400 py-10">
        {t("products_not_found")}
      </div>
    );
  }
  return (
    <div className="grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-5">
      {data.map((item: any) => (
        <Card
          key={item.id}
          title={item.name}
          image={item.image}
          slug={item.slug}
          id={item.id}
          category={item.category}
        />
      ))}
    </div>
  );
}
