'use client';
import { useRouter } from 'next/navigation';
import { useAllProductInfiniteQuery } from '@/feactures/inventory/hooks/use-query-products';
import { ProductCard } from '@/feactures/inventory/components/products/productCard';
// import { allProducts } from '@/feactures/inventory/schemas/inventory';
import { useRef, useEffect, useState } from 'react';
import { Input } from '@repo/shadcn/components/ui/input';
import { Button } from '@repo/shadcn/components/ui/button';

export function ProductList() {
  const router = useRouter();
  const lastProductRef = useRef(null);
  const [search, setSearch] = useState("")

  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isLoading
  } = useAllProductInfiniteQuery(search);

  useEffect(() => {
    if (!lastProductRef.current || !hasNextPage || isFetchingNextPage) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0]?.isIntersecting) {
          fetchNextPage();
        }
      },
      {
        root: null,
        rootMargin: '200px',
        threshold: 1.0,
      }
    );

    observer.observe(lastProductRef.current);

    return () => {
      observer.disconnect();
    };
  }, [hasNextPage, isFetchingNextPage, fetchNextPage]);

  // Funcion al hacer click en un producto
  const goTo = (id: number) => {
    router.push(`/dashboard/productos/${id}`);
  };

  // funcion para el buscador
  const formSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    const formdata = new FormData(e.currentTarget)
    setSearch(formdata.get('search') as string)
    console.log('submit')
  }

  const products = data?.pages.flatMap(page => page.data) || [];

  return (
    <div className="w-full grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
      <form onSubmit={formSubmit} action={''} className='col-span-full text-center py-3 flex gap-3'>
        <Input name='search' type='text' placeholder='Buscar...' className='' defaultValue={search}/>
        <Button variant={'outline'} className=''>Buscar</Button>
      </form>
      {isLoading ? (
        <section className="col-span-full text-center py-10">
          <p className="text-muted-foreground">Cargando productos...</p>
        </section>
      ) : products.length === 0 ? (
        <section className="col-span-full text-center py-10">
          <p className="text-muted-foreground">No hay productos disponibles en este momento.</p>
        </section>
      ) : (
        <>
          {products.map((item, index) => {
            const isLastElement = index === products.length - 1;           
            return (
              <div ref={isLastElement ? lastProductRef : null} key={item.id}>
                <ProductCard product={item} onClick={() => goTo(Number(item.id))} />
              </div>
            );
          })}
          {isFetchingNextPage && (
            <section className="col-span-full text-center py-10">
              <p className="text-muted-foreground">Cargando más productos...</p>
            </section>
          )}
        </>
      )}
    </div>
  );
}