import { useQuery } from '@tanstack/react-query';
import { useAtom } from 'jotai';
import { z } from 'zod';
import { searchQueryAtom } from '../store/atoms';
import { apiFetch } from '../services/apiClient';

// ---------------------------------------------------------------------------
// Zod schema — validate API response before rendering
// ---------------------------------------------------------------------------
const WordSchema = z.object({
  id: z.string().uuid(),
  text: z.string().min(1).max(255),
  createdAt: z.string().datetime(),
  status: z.enum(['active', 'to_be_defined']),
});

export type Word = z.infer<typeof WordSchema>;

const PagedWordSchema = z.object({
  data: z.array(WordSchema),
  total: z.number(),
  page: z.number(),
  limit: z.number(),
});

// ---------------------------------------------------------------------------
// Fetch helper
// ---------------------------------------------------------------------------
async function fetchWords(query: string): Promise<Word[]> {
  const response = await apiFetch(`/words?search=${encodeURIComponent(query)}&limit=50`);

  if (!response.ok) {
    throw new Error(`HTTP error ${response.status}`);
  }

  const raw: unknown = await response.json();
  return PagedWordSchema.parse(raw).data;
}

// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
/**
 * Searches words from the API.
 * The query is triggered only when the user has typed at least 3 characters.
 */
export function useWordSearch() {
  const [query] = useAtom(searchQueryAtom);
  const enabled = query.trim().length >= 3;

  const result = useQuery({
    queryKey: ['words', 'search', query],
    queryFn: () => fetchWords(query),
    enabled,
  });

  return {
    words: result.data ?? [],
    isLoading: result.isLoading,
    error: result.error,
    query,
    enabled,
  };
}
