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

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

/**
 * React hook for loading and managing trace data from IndexedDB
 * @param traceId - The ID of the trace to load, or null to load none
 * @returns Object containing trace data, loading state, error, and statistics
 */
export function useDatabaseTraceData(traceId: string | null): UseDatabaseTraceDataResult {
  const [traceData, setTraceData] = useState<TraceFile | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [stats, setStats] = useState<ReturnType<typeof getTraceStats> | null>(null)

  const loadData = async () => {
    if (!traceId) {
      setTraceData(null)
      setStats(null)
      setError(null)
      setLoading(false)
      return
    }

    try {
      setLoading(true)
      setError(null)
      
      // Initialize database if needed
      await traceDatabase.init()
      
      // Load trace from database
      const traceRecord = await traceDatabase.getTrace(traceId)
      
      if (!traceRecord) {
        throw new Error('Trace not found in database')
      }
      
      setTraceData(traceRecord.traceData)
      
      // Calculate statistics
      const traceStats = getTraceStats(traceRecord.traceData)
      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()
  }, [traceId])

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