"use client";
import { useEffect, useState } from "react";
import EmptyState from "./emptyData";
import { ProductModal } from "../productSection/ProductModal";
import { motion } from "framer-motion";
import { ProductCard } from "../productSection/ProductCard";
import axios from "axios";

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

export default function Products() {
  const [allProducts, setAllProducts] = useState<any>(null);
  const [selectedProduct, setSelectedProduct] = useState<any>(null);

  useEffect(() => {
    async function getData() {
      await axios.get("https://admin.promtechno.uz/api/products/").then((res) => {
        console.log("all data: ", res?.data);
        const allData = res?.data || [];
        setAllProducts(allData);
      });
    }
    getData();
  }, []);

  const handleViewDetails = (id: number) => {
    const product = allProducts.find((p: any) => p.id === id);
    if (product) {
      setSelectedProduct(product);
    }
  };
  return (
    <div className="py-20 max-w-[1200px] w-full mx-auto px-2 ">
      {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}
                onViewDetails={handleViewDetails}
              />
            </motion.div>
          ))}
        </div>
      ) : (
        <EmptyState page="products" />
      )}
      {/* Product Modal */}
      {selectedProduct && (
        <ProductModal
          product={selectedProduct}
          onClose={() => setSelectedProduct(null)}
        />
      )}
    </div>
  );
}
