'use client';

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

export interface Customer {
  id: number;
  name: string;
  estcob: string;
}

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

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

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