import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { leadsApi } from '@/api/leads'
import type { LeadFilters, LeadStatus } from '@/types/lead'

/**
 * Hook for fetching leads list
 */
export function useLeads(page = 1, perPage = 20, filters?: LeadFilters, language?: string) {
  return useQuery({
    queryKey: ['leads', page, perPage, filters, language],
    queryFn: () => leadsApi.getLeads(page, perPage, { ...filters, ...(language ? { language } : {}) }),
  })
}

/**
 * Hook for fetching single lead
 */
export function useLead(id: number) {
  return useQuery({
    queryKey: ['lead', id],
    queryFn: () => leadsApi.getLead(id),
    enabled: !!id,
  })
}

/**
 * Hook for fetching lead stats
 */
export function useLeadStats() {
  return useQuery({
    queryKey: ['lead-stats'],
    queryFn: () => leadsApi.getLeadStats(),
  })
}

/**
 * Hook for updating lead
 */
export function useUpdateLead() {
  const queryClient = useQueryClient()
  
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<{ lead_status: LeadStatus }> }) =>
      leadsApi.updateLead(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['leads'] })
      queryClient.invalidateQueries({ queryKey: ['lead-stats'] })
    },
  })
}

/**
 * Hook for updating lead status
 */
export function useUpdateLeadStatus() {
  const queryClient = useQueryClient()
  
  return useMutation({
    mutationFn: ({ id, status }: { id: number; status: LeadStatus }) =>
      leadsApi.updateLeadStatus(id, status),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['leads'] })
      queryClient.invalidateQueries({ queryKey: ['lead-stats'] })
      queryClient.invalidateQueries({ queryKey: ['lead', variables.id] })
    },
  })
}

/**
 * Hook for deleting lead
 */
export function useDeleteLead() {
  const queryClient = useQueryClient()
  
  return useMutation({
    mutationFn: (id: number) => leadsApi.deleteLead(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['leads'] })
      queryClient.invalidateQueries({ queryKey: ['lead-stats'] })
    },
  })
}










