"use client"
import { useMutation, useQuery } from "@tanstack/react-query"
import { createNewClient, fetchClients, removeClient, updateClient, createClient, getClients, getClientAppointments, getClientInsights, getClientDetails, getClientCalls, getWhatsAppSessions, fetchClientsByPlatform } from "../queries/clients"
import type { CreateClientPayload, ClientsResponse, CallLog, WhatsAppSession } from "@/types/clients"
import { useToaster } from "@/context/ToasterContext"
import { useRouter } from "next/navigation"
import { queryClient } from "../client"

export function useCreateClient() {
  const toast = useToaster()
  const router = useRouter()
  return useMutation({
    mutationKey: createClient,
    mutationFn: (payload: CreateClientPayload) => createNewClient(payload),
    onSuccess: data => {
      toast.showSuccess(data?.message || "Client created successfully!")
      queryClient.invalidateQueries({ queryKey: getClients })
      router.push("/dashboard/customers")
    },
    onError: error => {
      console.error("Client creation failed:", error)
      toast.showError("Failed to create client. Please try again.")
    }
  })
}

export function useGetClients({ page, limit, status }: { page?: number; limit?: number; status?: string } = {}) {
  return useQuery({
    queryKey: [...getClients, page, limit, status],
    queryFn: () => fetchClients(page, limit, status),
    refetchOnWindowFocus: false,
    staleTime: 5 * 60 * 1000 // 5 minutes
  })
}

export function useDeleteClient() {
  const toast = useToaster()
  return useMutation({
    mutationFn: (id: string) => removeClient(id),
    onSuccess: data => {
      toast.showSuccess(data?.message || "Client deleted successfully!")
      queryClient.invalidateQueries({ queryKey: getClients })
    },
    onError: error => {
      console.error("Client deletion failed:", error)
      toast.showError("Failed to delete client. Please try again.")
    }
  })
}

export function useUpdateClient() {
  const toast = useToaster()
  const router = useRouter()
  return useMutation({
    mutationFn: ({ id, payload }: { id: string; payload: CreateClientPayload }) => updateClient(id, payload),
    onSuccess: (data, variables) => {
      toast.showSuccess(data?.message || "Client updated successfully!")
      queryClient.invalidateQueries({ queryKey: getClients })
      queryClient.invalidateQueries({ queryKey: ["clients", "detail", variables.id] })
    },
    onError: error => {
      console.error("Client update failed:", error)
      toast.showError("Failed to update client. Please try again.")
    }
  })
}

export function useGetClientAppointments({ clientId, page = 1, limit = 10 }: { clientId: string, page?: number, limit?: number }) {
  return useQuery({
    queryKey: ["clients", "appointments", clientId, page, limit],
    queryFn: () => getClientAppointments(clientId, page, limit),
    enabled: !!clientId
  })
}

export function useGetClientInsights(clientId: string) {
  return useQuery({
    queryKey: ["clients", "insights", clientId],
    queryFn: () => getClientInsights(clientId),
    enabled: !!clientId
  })
}

export function useGetClientDetails(clientId: string, enabled: boolean = true) {
  return useQuery({
    queryKey: ["clients", "detail", clientId],
    queryFn: () => getClientDetails(clientId),
    enabled: !!clientId && enabled
  })
}

export function useGetClientCalls(clientId: string) {
  return useQuery<CallLog[]>({
    queryKey: ["clients", "calls", clientId],
    queryFn: () => getClientCalls(clientId),
    enabled: !!clientId
  })
}

export function useGetWhatsAppSessions(clientId: string) {
  return useQuery<WhatsAppSession[]>({
    queryKey: ["clients", "whatsapp", clientId],
    queryFn: () => getWhatsAppSessions(clientId),
    enabled: !!clientId
  })
}

export function useGetClientsByPlatform({ platformUsed, page = 1, limit = 10, enabled = false }: { platformUsed: string; page?: number; limit?: number; enabled?: boolean }) {
  return useQuery({
    queryKey: ["clients", "platform", platformUsed, page, limit],
    queryFn: () => fetchClientsByPlatform(platformUsed, page, limit),
    enabled,
    refetchOnWindowFocus: false,
    staleTime: 5 * 60 * 1000
  })
}
