'use client';

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

export interface Partner {
  id: number;
  cpf: string;
  nome: string;
}

export function usePartners(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: ['partners', debouncedSearchTerm],
    queryFn: () => orderService.findPartners(debouncedSearchTerm),
    enabled: isEnabled,
    staleTime: 1000 * 60 * 5,
    retry: 1,
    retryOnMount: false,
    refetchOnWindowFocus: false,
  });

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

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