import React, { useMemo, useState } 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 HostnameBreakdownProps {
  httpRequests: HTTPRequest[]
}

const HostnameBreakdown: React.FC<HostnameBreakdownProps> = ({ httpRequests }) => {
  const [showAllHostnames, setShowAllHostnames] = useState(false)

  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 hostnameBreakdown: CategoryBreakdown[] = useMemo(() => {
    const hostMap = new Map<string, HTTPRequest[]>()
    
    httpRequests.forEach(req => {
      const hostname = req.hostname || 'unknown'
      if (!hostMap.has(hostname)) {
        hostMap.set(hostname, [])
      }
      hostMap.get(hostname)!.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(hostMap.entries()).map(([hostname, 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: hostname,
        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 Hostname</h3>
      <div className={styles.breakdownTable}>
        <BreakdownTableHeader categoryLabel="Hostname" />
        {(showAllHostnames ? hostnameBreakdown : hostnameBreakdown.slice(0, 10)).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>
      {hostnameBreakdown.length > 10 && (
        <div className={styles.moreInfo}>
          {showAllHostnames ? (
            <>
              Showing all {hostnameBreakdown.length} hostnames
              <button 
                onClick={() => setShowAllHostnames(false)}
                className={styles.toggleButton}
              >
                Show Top 10 Only
              </button>
            </>
          ) : (
            <>
              Showing top 10 of {hostnameBreakdown.length} hostnames
              <button 
                onClick={() => setShowAllHostnames(true)}
                className={styles.toggleButton}
              >
                Show All Hostnames
              </button>
            </>
          )}
        </div>
      )}
    </div>
  )
}

export default HostnameBreakdown