import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { inquiryService } from '../services/inquiryService'
import type { InquiryFilters, CreateInquiryInput, CreateOfferInput } from '../provider/IInquiryProvider'
import type { Attachment, InquiryMessage } from '../domain/inquiry'
import { useToastStore } from '../stores/toastStore'

export function useActiveInquiries(filters?: InquiryFilters) {
  return useQuery({
    queryKey: ['inquiries', 'active', filters ?? {}],
    queryFn: () => inquiryService.getActiveInquiries(filters),
    select: (res) => res.data ?? [],
  })
}

export function useInquiryById(id: string) {
  return useQuery({
    queryKey: ['inquiry', id],
    queryFn: () => inquiryService.getInquiryById(id),
    enabled: !!id,
    select: (res) => res.data ?? null,
  })
}

export function useSendInquiryReply() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({
      inquiryId,
      payload,
    }: {
      inquiryId: string
      payload: { subject?: string; body: string; attachments?: Attachment[]; senderType?: InquiryMessage['senderType']; senderName?: string }
    }) => inquiryService.sendInquiryReply(inquiryId, payload),
    onSuccess: (_data, { inquiryId }) => {
      qc.invalidateQueries({ queryKey: ['inquiry', inquiryId] })
      qc.invalidateQueries({ queryKey: ['inquiries'] })
    },
    onError: () => {
      useToastStore.getState().showToast('Antwort konnte nicht gesendet werden.', 'error')
    },
  })
}

/** Demand→Supply: neue Anfrage erstellen (ersetzt die alte Zustand-Insel). */
export function useCreateInquiry() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (input: CreateInquiryInput) => inquiryService.createInquiry(input),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['inquiries'] })
    },
    onError: () => {
      useToastStore.getState().showToast('Anfrage konnte nicht gesendet werden.', 'error')
    },
  })
}

/** Supply→Demand: Angebot als Konversation im Nachfrager-Postfach materialisieren. */
export function useCreateOffer() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (input: CreateOfferInput) => inquiryService.createOffer(input),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['inquiries'] })
    },
  })
}

export function useMarkThreadAsRead() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (id: string) => inquiryService.markThreadAsRead(id),
    onSuccess: (_data, id) => {
      qc.invalidateQueries({ queryKey: ['inquiry', id] })
      qc.invalidateQueries({ queryKey: ['inquiries'] })
    },
  })
}
