// Este componente maneja la lista de encuestas en el panel de administración
// Funcionalidades:
// - Muestra todas las encuestas en una tabla
// - Permite editar encuestas existentes
// - Permite eliminar encuestas con confirmación
// - Muestra el estado (publicada/borrador), fechas y conteo de respuestas
'use client';

import { Button } from '@repo/shadcn/button';
import { useRouter } from 'next/navigation';
import { useAllSurveysInfiniteQuery } from '@/feactures/surveys/hooks/use-query-surveys';
import { SurveyCard } from '@/feactures/surveys/components/survey-card';

import { SurveyAnswerForUser } from '../schemas/survey';

import { useEffect, useRef, useState } from 'react';
import { Input } from '@repo/shadcn/components/ui/input';

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

  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isLoading
  } = useAllSurveysInfiniteQuery(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]);

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

  // 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 handleRespond = (surveyId: number) => {
    router.push(`/dashboard/encuestas/${surveyId}/responder`);
  };

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <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>
      ) : surveys.length === 0 ? (
        <section className="col-span-full text-center py-10">
          <p className="text-muted-foreground">No hay encuestas disponibles en este momento.</p>
        </section>
      ) : (
        <>
          {surveys.map((data: SurveyAnswerForUser, index) => {
            const isLastElement = index === surveys.length - 1;
            return (
              <div ref={isLastElement ? lastProductRef : null} key={data.surveys.id}>
                <SurveyCard data={data} onClick={handleRespond}/>
              </div>
            )
          })}
          {isFetchingNextPage && (
            <section className="col-span-full text-center py-10">
              <p className="text-muted-foreground">Cargando más productos...</p>
            </section>
          )}
        </>
      )}
    </div>
  )
}