"use client";
import { useEffect, useState, useRef, useCallback } from "react";
import axios from "axios";
//import { Product } from "@/app/lib/products/product";
import Image from "next/image";

interface Product {
  id: number;
  name: string;
  price: number;
  category: string;
  // Add any other fields that your product has
}

interface ApiResponse {
  products: Product[];
  total: number;
}

interface Props {
  selectedCategories: string[];
  sortBy: string;
}

export default function Products({ selectedCategories, sortBy }: Props) {
  const [products, setProducts] = useState<Product[]>([]);
  const [page, setPage] = useState(0);
  const [loading, setLoading] = useState(false);
  const loader = useRef(null);

  const fetchProducts = useCallback(async () => {
    setLoading(true);
    const limit = 10;
    const skip = page * limit;

    try {
      // Typing the response to ApiResponse
      const res = await axios.get<ApiResponse>(
        `https://dummyjson.com/products?limit=${limit}&skip=${skip}`,
      );
      
      let data: Product[] = res.data.products;

      // Filter by category if any
      if (selectedCategories.length > 0) {
        data = data.filter((p) => selectedCategories.includes(p.category));
      }

      // Add sorting logic based on `sortBy` (e.g., price, name)
      if (sortBy === 'price_low_to_high') {
        data = data.sort((a, b) => a.price - b.price);
      } else if (sortBy === 'price_high_to_low') {
        data = data.sort((a, b) => b.price - a.price);
      } else if (sortBy === 'name') {
        data = data.sort((a, b) => a.name.localeCompare(b.name));
      }

      // Set the filtered and sorted data
      setProducts(data);
    } catch (error) {
      console.error('Error fetching products:', error);
    } finally {
      setLoading(false);
    }
  }, [page, selectedCategories, sortBy]);

  useEffect(() => {
    fetchProducts();
  }, [fetchProducts]);

  return (
    <div>
      <div className="grid grid-cols-2 gap-4 md:gap-10 md:grid-cols-3">
        {products.map((product, index) => (
          <div
            key={`${product.id}_${index}`}
            className="flex flex-col gap-5 bg-white p-5"
          >
            {/* <Image
              src={product.images}
              alt={product.title}
              width={600}
              height={800}
              className="img-responsive"
            /> */}
            <div className="flex flex-col">
              <p className="font-bogart text-base font-medium">
                ${product.price}
              </p>
              <div className="mt-2 text-sm">{product.name}</div>
            </div>
          </div>
        ))}
      </div>
      <div ref={loader} className="mt-4 flex flex-col h-20 items-center justify-center align-middle">
        {loading && <p>Loading more products...</p>}
      </div>
    </div>
  );
}
