"use client";
import InnerProductcard from "@/components/cards/innerProductcard";
import { EmptyState } from "@/components/emptyState";
import Text from "@/components/lib_components/text";
import Title from "@/components/lib_components/title";
import { LoadingSkeleton } from "@/components/loadingProduct";
import { useSubCategory } from "@/store/subCategory";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";

const baseUrl = "https://api.spes-texnika.uz/api/v1/subcategory/?category=";

export default function CartType() {
  const initialSubCategory = useSubCategory(
    (state) => state.initialSubCategory,
  );
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const pathname = usePathname();
  const lang = pathname.split("/")[1];
  const [cars, setCars] = useState<any[]>([]);

  useEffect(() => {
    // Agar ID bo'lmasa, fetchni ishga tushirma for gitea
    if (!initialSubCategory.id) {
      setLoading(false);
      return;
    }

    const fetchProducts = async () => {
      try {
        setLoading(true);
        setError(null);

        const response = await fetch(`${baseUrl}${initialSubCategory.id}`, {
          headers: {
            "Accept-Language": lang,
          },
        });

        if (!response.ok) {
          throw new Error("Server xatosi");
        }

        const result = await response.json();
        console.log("inner car: ", result)

        // Data array ekanligini tekshirish
        if (result?.data) {
          if (Array.isArray(result.data)) {
            setCars(result.data);
          } else {
            // Agar object bo'lsa, uni array ichiga o'rab qo'yamiz
            setCars([result.data]);
          }
        } else {
          setCars([]);
        }
      } catch (error) {
        console.log("Xatolik: ", error);
        setError(error instanceof Error ? error.message : "Noma'lum xatolik");
        setCars([]);
      } finally {
        setLoading(false);
      }
    };

    fetchProducts();
  }, [lang]); // initialCar.id ham dependency ga qo'shildi

  return (
    <div dir="ltr" className="my-20">
      <Title text="tex-rent" />

      {/* Error message */}
      {error && (
        <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-600 text-center">
            <Text txt="downloadError" />: {error}
          </p>
        </div>
      )}

      {/* car type groups */}
      <div className="mt-10 grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-5 max-w-[1200px] w-full mx-auto px-4">
        {loading ? (
          <LoadingSkeleton />
        ) : cars.length > 0 ? (
          cars.map((car, index) => (
            <InnerProductcard key={car.id || index} data={car} />
          ))
        ) : (
          <EmptyState />
        )}
      </div>
    </div>
  );
}
