import { useState, useCallback } from 'react'
import { handoffsApi } from '@/api'
import type { HandoffCreateRequest, HandoffResponse, QueueItemResponse } from '@/types/branching'
import { toast } from '@/lib/toast'

export function useHandoff() {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [queue, setQueue] = useState<QueueItemResponse[]>([])
  const [isLoadingQueue, setIsLoadingQueue] = useState(false)

  const createHandoff = useCallback(async (sessionId: string, data: HandoffCreateRequest): Promise<HandoffResponse | null> => {
    setIsSubmitting(true)
    try {
      const result = await handoffsApi.createHandoff(sessionId, data)
      toast.success(data.intent === 'park' ? 'Session parked' : 'Session escalated')
      return result
    } catch {
      toast.error('Failed to hand off session')
      return null
    } finally {
      setIsSubmitting(false)
    }
  }, [])

  const claimHandoff = useCallback(async (sessionId: string, handoffId: string): Promise<HandoffResponse | null> => {
    try {
      const result = await handoffsApi.claimHandoff(sessionId, handoffId)
      toast.success('Session claimed')
      return result
    } catch {
      toast.error('Failed to claim session')
      return null
    }
  }, [])

  const loadQueue = useCallback(async () => {
    setIsLoadingQueue(true)
    try {
      const items = await handoffsApi.getQueue()
      setQueue(items)
    } catch {
      toast.error('Failed to load queue')
    } finally {
      setIsLoadingQueue(false)
    }
  }, [])

  return { isSubmitting, queue, isLoadingQueue, createHandoff, claimHandoff, loadQueue }
}
