"use client";
import { useEffect, useState } from "react";
import EmptyState from "./emptyData";
import { motion } from "framer-motion";
import { ProductCard } from "../productSection/ProductCard";
import axios from "axios";
import Loading from "../loading";
import { generateSlug } from "@/lib/slug";
import { getAllProducts } from "@/lib/api";

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0 },
};

export default function Products() {
  const [allProducts, setAllProducts] = useState<any>([]);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    async function getData() {
      setLoading(true);
      const products = await getAllProducts();
      setAllProducts(
        products.map((product: any) => ({
          ...product,
          slug: generateSlug(product.name_uz),
        }))
      );
      setLoading(false);
    }
    getData();
  }, []);

  return (
    <div className="py-20 max-w-[1200px] w-full mx-auto px-2 ">
      {loading && (
        <div className="w-full flex items-center justify-center">
          <Loading />
        </div>
      )}
      {loading || (allProducts && allProducts.length > 0) ? (
        <div className="grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-4">
          {allProducts.map((product: any) => (
            <motion.div key={product.id} variants={itemVariants}>
              <ProductCard product={product} />
            </motion.div>
          ))}
        </div>
      ) : (
        <EmptyState page="products" />
      )}
    </div>
  );
}
