import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { shortlistService } from '../services/shortlistService'
import type { CreateShortlistInput, UpdateShortlistInput, ShortlistItemInput } from '../domain/shortlist'
import { useToastStore } from '../stores/toastStore'

export function useShortlists() {
  return useQuery({
    queryKey: ['shortlists'],
    queryFn: () => shortlistService.getAll(),
    select: (res) => res.data ?? [],
  })
}

export function useShortlist(id: string) {
  return useQuery({
    queryKey: ['shortlist', id],
    queryFn: () => shortlistService.getById(id),
    enabled: !!id,
    select: (res) => res.data ?? null,
  })
}

export function useCreateShortlist() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (input: CreateShortlistInput) => shortlistService.create(input),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['shortlists'] })
    },
    onError: () => {
      useToastStore.getState().showToast('Merkliste konnte nicht erstellt werden.', 'error')
    },
  })
}

export function useAddToShortlist() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ shortlistId, item }: { shortlistId: string; item: ShortlistItemInput }) =>
      shortlistService.addItem(shortlistId, item),
    onSuccess: (_data, { shortlistId }) => {
      queryClient.invalidateQueries({ queryKey: ['shortlists'] })
      queryClient.invalidateQueries({ queryKey: ['shortlist', shortlistId] })
    },
    onError: () => {
      useToastStore.getState().showToast('Eintrag konnte nicht zur Merkliste hinzugefügt werden.', 'error')
    },
  })
}

export function useRemoveFromShortlist() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ shortlistId, resultId }: { shortlistId: string; resultId: string }) =>
      shortlistService.removeItem(shortlistId, resultId),
    onSuccess: (_data, { shortlistId }) => {
      queryClient.invalidateQueries({ queryKey: ['shortlists'] })
      queryClient.invalidateQueries({ queryKey: ['shortlist', shortlistId] })
    },
    onError: () => {
      useToastStore.getState().showToast('Eintrag konnte nicht von der Merkliste entfernt werden.', 'error')
    },
  })
}

export function useUpdateShortlist() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateShortlistInput }) =>
      shortlistService.update(id, data),
    onSuccess: (_data, { id }) => {
      queryClient.invalidateQueries({ queryKey: ['shortlists'] })
      queryClient.invalidateQueries({ queryKey: ['shortlist', id] })
    },
    onError: () => {
      useToastStore.getState().showToast('Merkliste konnte nicht aktualisiert werden.', 'error')
    },
  })
}
