import { useState, useEffect } from 'react'
import type { TraceFile } from '../../types/trace'
import { loadTraceFile, getTraceStats } from '../utils/traceLoader'

interface UseTraceDataResult {
  traceData: TraceFile | null
  loading: boolean
  error: string | null
  stats: ReturnType<typeof getTraceStats> | null
  reload: () => void
}

/**
 * React hook for loading and managing trace data
 * @returns Object containing trace data, loading state, error, and statistics
 */
export function useTraceData(): UseTraceDataResult {
  const [traceData, setTraceData] = useState<TraceFile | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [stats, setStats] = useState<ReturnType<typeof getTraceStats> | null>(null)

  const loadData = async () => {
    try {
      setLoading(true)
      setError(null)
      
      const data = await loadTraceFile()
      setTraceData(data)
      
      // Calculate statistics
      const traceStats = getTraceStats(data)
      setStats(traceStats)
      
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'
      setError(errorMessage)
      setTraceData(null)
      setStats(null)
    } finally {
      setLoading(false)
    }
  }

  const reload = () => {
    loadData()
  }

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

  return {
    traceData,
    loading,
    error,
    stats,
    reload
  }
}