import { useMemo } from 'react'
import { useDatabaseTraceData } from '../../hooks/useDatabaseTraceData'
import { processHTTPRequests } from '../httprequestviewer/lib/httpRequestProcessor'
import { addRequestPostProcessing } from '../httprequestviewer/lib/requestPostProcessor'
import { analyzeCDN, analyzeQueueReason } from '../httprequestviewer/lib/analysisUtils'
import { assignConnectionNumbers } from '../httprequestviewer/lib/connectionUtils'
import sortRequests from '../httprequestviewer/lib/sortRequests'
import RequestDataSummary from './RequestDataSummary'
import ResourceTypeBreakdown from './ResourceTypeBreakdown'
import StatusCodeBreakdown from './StatusCodeBreakdown'
import HostnameBreakdown from './HostnameBreakdown'
import styles from './RequestBreakdown.module.css'

interface RequestBreakdownProps {
  traceId: string | null
}

interface BreakdownStats {
  totalRequests: number
  totalSize: number
  totalDuration: number
  averageResponseTime: number
  successRate: number
  cacheHitRate: number
}


const RequestBreakdown: React.FC<RequestBreakdownProps> = ({ traceId }) => {
  const { traceData, loading, error } = useDatabaseTraceData(traceId)

  const httpRequests = useMemo(() => {
    if (!traceData) return []
    const requests = processHTTPRequests(traceData.traceEvents)
    const sortedRequests = sortRequests(requests)
    const processedRequests = addRequestPostProcessing(sortedRequests, analyzeQueueReason, analyzeCDN)
    return assignConnectionNumbers(processedRequests)
  }, [traceData])

  const overallStats: BreakdownStats = useMemo(() => {
    if (httpRequests.length === 0) {
      return {
        totalRequests: 0,
        totalSize: 0,
        totalDuration: 0,
        averageResponseTime: 0,
        successRate: 0,
        cacheHitRate: 0
      }
    }

    const totalSize = httpRequests.reduce((sum, req) => {
      const size = req.contentLength || req.encodedDataLength || 0
      return sum + size
    }, 0)

    const totalDuration = httpRequests.reduce((sum, req) => {
      return sum + (req.timing.duration || 0)
    }, 0)

    const totalResponseTime = httpRequests.reduce((sum, req) => {
      return sum + (req.timing.totalResponseTime || 0)
    }, 0)

    const successfulRequests = httpRequests.filter(req => 
      req.statusCode && req.statusCode >= 200 && req.statusCode < 300
    ).length

    const cachedRequests = httpRequests.filter(req => req.fromCache).length

    return {
      totalRequests: httpRequests.length,
      totalSize,
      totalDuration,
      averageResponseTime: totalResponseTime / httpRequests.length,
      successRate: (successfulRequests / httpRequests.length) * 100,
      cacheHitRate: (cachedRequests / httpRequests.length) * 100
    }
  }, [httpRequests])


  if (loading) {
    return (
      <div className={styles.container}>
        <div className={styles.loading}>Loading request breakdown...</div>
      </div>
    )
  }

  if (error) {
    return (
      <div className={styles.container}>
        <div className={styles.error}>
          <h3>Error Loading Data</h3>
          <p>{error}</p>
        </div>
      </div>
    )
  }

  return (
    <div className={styles.container}>
      <h2>Request Data Breakdown</h2>
      
      {/* Overall Stats */}
      <RequestDataSummary
        totalRequests={overallStats.totalRequests}
        totalSize={overallStats.totalSize}
        averageResponseTime={overallStats.averageResponseTime}
        successRate={overallStats.successRate}
        cacheHitRate={overallStats.cacheHitRate}
      />

      <ResourceTypeBreakdown httpRequests={httpRequests} />
      <StatusCodeBreakdown httpRequests={httpRequests} />
      <HostnameBreakdown httpRequests={httpRequests} />
    </div>
  )
}

export default RequestBreakdown