import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  createEncounter,
  updateEncounter,
  deleteEncounter,
  fetchEvolutions,
  fetchForms,
  bulkRandomizeEncounters,
} from '../api/encounters'
import type { CreateEncounterInput, UpdateEncounterInput } from '../types/game'

export function useCreateEncounter(runId: number) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateEncounterInput) => createEncounter(runId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['runs', runId] })
    },
  })
}

export function useUpdateEncounter(runId: number) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({
      id,
      data,
    }: {
      id: number
      data: UpdateEncounterInput
    }) => updateEncounter(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['runs', runId] })
    },
  })
}

export function useDeleteEncounter(runId: number) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: number) => deleteEncounter(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['runs', runId] })
    },
  })
}

export function useEvolutions(pokemonId: number | null, region?: string) {
  return useQuery({
    queryKey: ['evolutions', pokemonId, region],
    queryFn: () => fetchEvolutions(pokemonId!, region),
    enabled: pokemonId !== null,
  })
}

export function useForms(pokemonId: number | null) {
  return useQuery({
    queryKey: ['forms', pokemonId],
    queryFn: () => fetchForms(pokemonId!),
    enabled: pokemonId !== null,
  })
}

export function useBulkRandomize(runId: number) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: () => bulkRandomizeEncounters(runId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['runs', runId] })
    },
  })
}
