import { useState, useCallback } from 'react'
import { resolutionsApi } from '@/api'
import type { ResolutionOutputResponse, PushDestination } from '@/types/branching'
import { toast } from '@/lib/toast'

export function useResolutionOutputs(sessionId: string) {
  const [outputs, setOutputs] = useState<ResolutionOutputResponse[]>([])
  const [isLoading, setIsLoading] = useState(false)

  const loadOutputs = useCallback(async () => {
    setIsLoading(true)
    try {
      const data = await resolutionsApi.getOutputs(sessionId)
      setOutputs(data.outputs)
    } catch {
      toast.error('Failed to load resolution outputs')
    } finally {
      setIsLoading(false)
    }
  }, [sessionId])

  const editOutput = useCallback(async (outputId: string, content: string) => {
    try {
      const updated = await resolutionsApi.editOutput(sessionId, outputId, { edited_content: content })
      setOutputs(prev => prev.map(o => o.id === updated.id ? updated : o))
      toast.success('Changes saved')
    } catch {
      toast.error('Failed to save changes')
    }
  }, [sessionId])

  const pushOutput = useCallback(async (outputId: string, destination: PushDestination) => {
    try {
      await resolutionsApi.pushOutput(sessionId, outputId, { destination })
      toast.success(`Pushed to ${destination}`)
      await loadOutputs()
    } catch {
      toast.error('Failed to push output')
    }
  }, [sessionId, loadOutputs])

  return { outputs, isLoading, loadOutputs, editOutput, pushOutput }
}
