'use client';

import { useQuery } from '@tanstack/react-query';

import { apiFetch } from '@/lib/api/client';
import { useDebounce } from '@/hooks/use-debounce';

// ─── Types ────────────────────────────────────────────────────────────────────

interface SearchResults {
  clients: Array<{ id: string; fullName: string }>;
  interests: Array<{
    id: string;
    clientName: string;
    berthMooringNumber: string | null;
    pipelineStage: string;
  }>;
  berths: Array<{ id: string; mooringNumber: string; area: string | null; status: string }>;
  yachts: Array<{
    id: string;
    name: string;
    hullNumber: string | null;
    registration: string | null;
  }>;
  companies: Array<{
    id: string;
    name: string;
    legalName: string | null;
    taxId: string | null;
  }>;
}

// ─── Hook ─────────────────────────────────────────────────────────────────────

export function useSearch(query: string) {
  const debouncedQuery = useDebounce(query, 300);

  const searchQuery = useQuery<SearchResults>({
    queryKey: ['search', debouncedQuery],
    queryFn: () =>
      apiFetch<SearchResults>(`/api/v1/search?q=${encodeURIComponent(debouncedQuery)}`),
    enabled: debouncedQuery.length >= 2,
    staleTime: 30_000,
  });

  const recentQuery = useQuery<{ searches: string[] }>({
    queryKey: ['search', 'recent'],
    queryFn: () => apiFetch<{ searches: string[] }>('/api/v1/search/recent'),
    staleTime: 60_000,
  });

  return {
    results: searchQuery.data,
    isLoading: searchQuery.isLoading,
    recentSearches: recentQuery.data?.searches ?? [],
  };
}
