"use client"
import { useMutation, useQuery } from "@tanstack/react-query"
import {
  createReminder,
  createNewReminder,
  fetchReminders,
  getReminders,
  removeReminder,
  updateReminder,
  getReminderById,
  getReminderDetails,
  getReminderDefaults,
  fetchReminderDefaults,
  getNotifications,
  fetchNotifications,
  markAllNotificationsRead,
  markAllNotificationsAsRead,
  markNotificationRead,
  getStoredNotificationById
} from "../queries/reminders"
import type { CreateReminderPayload, RemindersResponse, Reminder, NotificationsResponse } from "@/types/reminders"
import { useToaster } from "@/context/ToasterContext"
import { queryClient } from "../client"

export function useCreateReminder() {
  const toast = useToaster()
  return useMutation({
    mutationKey: createReminder,
    mutationFn: (payload: CreateReminderPayload) => createNewReminder(payload),
    onSuccess: data => {
      toast.showSuccess("Reminder created successfully!")
      queryClient.invalidateQueries({ queryKey: getReminders })
    },
    onError: error => {
      console.error("Reminder creation failed:", error)
      toast.showError("Failed to create reminder. Please try again.")
    }
  })
}

export function useGetReminders() {
  return useQuery<Reminder[]>({
    queryKey: getReminders,
    queryFn: fetchReminders,
    refetchOnWindowFocus: false
  })
}

export function useDeleteReminder() {
  const toast = useToaster()
  return useMutation({
    mutationFn: (id: string) => removeReminder(id),
    onSuccess: data => {
      toast.showSuccess("Reminder deleted successfully!")
      queryClient.invalidateQueries({ queryKey: getReminders })
    },
    onError: error => {
      toast.showError("Failed to delete reminder. Please try again.")
    }
  })
}

export function useUpdateReminder() {
  const toast = useToaster()
  return useMutation({
    mutationFn: ({ id, payload }: { id: string; payload: Partial<CreateReminderPayload> }) => updateReminder(id, payload),
    onSuccess: data => {
      toast.showSuccess("Reminder updated successfully!")
      queryClient.invalidateQueries({ queryKey: getReminders })
      queryClient.invalidateQueries({ queryKey: getReminderDefaults })
    },
    onError: error => {
      console.error("Reminder update failed:", error)
      toast.showError("Failed to update reminder. Please try again.")
    }
  })
}

export function useGetReminderById(id: string) {
  return useQuery<Reminder>({
    queryKey: getReminderById(id),
    queryFn: () => getReminderDetails(id),
    enabled: !!id,
    refetchOnWindowFocus: false,
    refetchOnMount: true
  })
}

export function useGetReminderDefaults() {
  return useQuery<Reminder[]>({
    queryKey: getReminderDefaults,
    queryFn: fetchReminderDefaults,
    refetchOnWindowFocus: false
  })
}

export function useGetNotifications(type?: string) {
  return useQuery<NotificationsResponse>({
    queryKey: [...getNotifications, type],
    queryFn: () => fetchNotifications(type),
    refetchOnWindowFocus: false,
    refetchInterval: 60000 // Refetch every 60 seconds
  })
}

export function useMarkAllNotificationsAsRead() {
  const toast = useToaster()
  return useMutation({
    mutationKey: markAllNotificationsRead,
    mutationFn: markAllNotificationsAsRead,
    onSuccess: () => {
      toast.showSuccess("All notifications marked as read!")
      queryClient.invalidateQueries({ queryKey: getNotifications })
    },
    onError: (error) => {
      console.error("Mark all notifications as read failed:", error)
      toast.showError("Failed to mark notifications as read. Please try again.")
    }
  })
}

export function useMarkNotificationAsRead() {
  return useMutation({
    mutationFn: (id: string) => markNotificationRead(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: getNotifications })
    },
    onError: (error) => {
      console.error("Mark notification as read failed:", error)
    }
  })
}

export function useGetStoredNotificationById(id: string) {
  return useQuery<Notification>({
    queryKey: ["notifications", "detail", id],
    queryFn: () => getStoredNotificationById(id),
    enabled: !!id,
    refetchOnWindowFocus: false
  })
}
