'use client';

import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { orderService } from '../api/order.service';

export interface Product {
  id: number;
  description: string;
}

export function useProducts(searchTerm: string) {
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState(searchTerm);

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
    }, 300);

    return () => clearTimeout(timer);
  }, [searchTerm]);

  const isEnabled = debouncedSearchTerm.length >= 2;

  const query = useQuery({
    queryKey: ['products', debouncedSearchTerm],
    queryFn: () => orderService.findProducts(debouncedSearchTerm),
    enabled: isEnabled,
    staleTime: 1000 * 60 * 5,
    retry: 1,
    retryOnMount: false,
    refetchOnWindowFocus: false,
  });

  const options =
    query.data?.map((product, index) => ({
      value: product.id.toString(),
      label: product.description,
      id: `product-${product.id}-${index}`,
      product: product,
    })) ?? [];

  return {
    ...query,
    options,
  };
}
