import { useState, useEffect, useCallback } from 'react'
import { psaContextApi, type TicketContext } from '@/api/psaContext'

interface UseTicketContextResult {
  context: TicketContext | null
  loading: boolean
  error: string | null
  refresh: () => void
}

export function useTicketContext(
  psaTicketId: string | null | undefined,
  psaConnectionId: string | null | undefined
): UseTicketContextResult {
  const [context, setContext] = useState<TicketContext | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const fetchContext = useCallback(async () => {
    if (!psaTicketId || !psaConnectionId) return

    setLoading(true)
    setError(null)
    try {
      const data = await psaContextApi.getTicketContext(psaTicketId)
      setContext(data)
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to load ticket context'
      setError(message)
    } finally {
      setLoading(false)
    }
  }, [psaTicketId, psaConnectionId])

  useEffect(() => {
    fetchContext()
  }, [fetchContext])

  return { context, loading, error, refresh: fetchContext }
}
