"use client"

import { useCallback } from "react"
import { toast } from "sonner"
import { eventRescheduleApiPayload, shiftedEventRange } from "@/lib/agenda/agenda-move-event"
import { isExternalCalendarId } from "@/lib/agenda/agenda-calendar-visibility"
import type { AgendaEvent } from "@/lib/agenda/agenda-types"
import { useUpdateAgendaEvent } from "@/lib/api/hooks/use-calendar-mutations"

export function useAgendaEventMove() {
  const updateMutation = useUpdateAgendaEvent()

  const moveEvent = useCallback(
    async (event: AgendaEvent, targetStart: Date) => {
      if (isExternalCalendarId(event.calendarId)) return
      const { start, end } = shiftedEventRange(event, targetStart)
      try {
        await updateMutation.mutateAsync({
          path: event.path,
          etag: event.etag,
          event: eventRescheduleApiPayload(event, start, end),
        })
        toast.success("Événement déplacé")
      } catch {
        toast.error("Impossible de déplacer l'événement")
      }
    },
    [updateMutation],
  )

  return { moveEvent, isMoving: updateMutation.isPending }
}
