import React, { useMemo } from 'react'
import type { HTTPRequest } from '../httprequestviewer/types/httpRequest'
import BreakdownTableHeader from './BreakdownTableHeader'
import styles from './RequestBreakdown.module.css'

interface CategoryBreakdown {
  name: string
  count: number
  percentage: number
  totalSize: number
  sizePercentage: number
  totalResponseTime: number
  responseTimePercentage: number
  averageResponseTime: number
}

interface ResourceTypeBreakdownProps {
  httpRequests: HTTPRequest[]
}

const ResourceTypeBreakdown: React.FC<ResourceTypeBreakdownProps> = ({ httpRequests }) => {
  const formatSize = (bytes: number): string => {
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
    return `${(bytes / 1024 / 1024).toFixed(1)} MB`
  }

  const formatDuration = (microseconds: number): string => {
    if (microseconds < 1000) return `${microseconds.toFixed(0)} μs`
    if (microseconds < 1000000) return `${(microseconds / 1000).toFixed(1)} ms`
    return `${(microseconds / 1000000).toFixed(2)} s`
  }

  const resourceTypeBreakdown: CategoryBreakdown[] = useMemo(() => {
    const typeMap = new Map<string, HTTPRequest[]>()
    
    httpRequests.forEach(req => {
      const type = req.resourceType || 'unknown'
      if (!typeMap.has(type)) {
        typeMap.set(type, [])
      }
      typeMap.get(type)!.push(req)
    })

    // Calculate total size and response time across all requests for percentage calculations
    const totalAllSize = httpRequests.reduce((sum, req) => {
      return sum + (req.contentLength || req.encodedDataLength || 0)
    }, 0)

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

    return Array.from(typeMap.entries()).map(([type, requests]) => {
      const totalSize = requests.reduce((sum, req) => {
        return sum + (req.contentLength || req.encodedDataLength || 0)
      }, 0)
      
      const totalResponseTime = requests.reduce((sum, req) => {
        return sum + (req.timing.totalResponseTime || 0)
      }, 0)

      return {
        name: type,
        count: requests.length,
        percentage: (requests.length / httpRequests.length) * 100,
        totalSize,
        sizePercentage: totalAllSize > 0 ? (totalSize / totalAllSize) * 100 : 0,
        totalResponseTime,
        responseTimePercentage: totalAllResponseTime > 0 ? (totalResponseTime / totalAllResponseTime) * 100 : 0,
        averageResponseTime: totalResponseTime / requests.length
      }
    }).sort((a, b) => b.count - a.count)
  }, [httpRequests])

  return (
    <div className={styles.breakdownSection}>
      <h3>By Resource Type</h3>
      <div className={styles.breakdownTable}>
        <BreakdownTableHeader categoryLabel="Resource Type" />
        {resourceTypeBreakdown.map(item => (
          <div key={item.name} className={styles.tableRow}>
            <span className={styles.categoryName}>{item.name}</span>
            <span>{item.count}</span>
            <div className={styles.percentageCell}>
              <span>{item.percentage.toFixed(1)}%</span>
              <div className={styles.progressBar}>
                <div 
                  className={styles.progressFill}
                  style={{ width: `${item.percentage}%` }}
                ></div>
              </div>
            </div>
            <span>{formatSize(item.totalSize)}</span>
            <div className={styles.percentageCell}>
              <span>{item.sizePercentage.toFixed(1)}%</span>
              <div className={styles.progressBar}>
                <div 
                  className={styles.progressFill}
                  style={{ width: `${item.sizePercentage}%` }}
                ></div>
              </div>
            </div>
            <span>{formatDuration(item.totalResponseTime)}</span>
            <div className={styles.percentageCell}>
              <span>{item.responseTimePercentage.toFixed(1)}%</span>
              <div className={styles.progressBar}>
                <div 
                  className={styles.progressFill}
                  style={{ width: `${item.responseTimePercentage}%` }}
                ></div>
              </div>
            </div>
            <span>{formatDuration(item.averageResponseTime)}</span>
          </div>
        ))}
      </div>
    </div>
  )
}

export default ResourceTypeBreakdown