import React from 'react'
import RequestRowDetails from './RequestRowDetails'
import styles from './RequestRowSummary.module.css'
import type { HTTPRequest } from './types/httpRequest'

// Import utility functions
import { formatDuration, formatSize, formatDataRate } from './lib/formatUtils'
import {
  getTotalResponseTimeClass,
  getServerLatencyClass,
  getDurationClass,
  getDataRateClass,
  getSizeClass,
  getQueueAnalysisIcon,
  getCDNIcon,
  getCDNDisplayName,
  getPriorityIcon,
  getProtocolClass,
  getConnectionClass
} from './lib/colorUtils'
import { truncateUrl } from './lib/urlUtils'

interface RequestRowSummaryProps {
  request: HTTPRequest
  showQueueAnalysis: boolean
  isExpanded: boolean
  onToggleRowExpansion: (requestId: string) => void
  visibleColumns: Record<string, boolean>
}

const RequestRowSummary: React.FC<RequestRowSummaryProps> = ({
  request,
  showQueueAnalysis,
  isExpanded,
  onToggleRowExpansion,
  visibleColumns
}) => {
  return (
    <>
      <tr className={styles.default} key={request.requestId}
      onClick={() => onToggleRowExpansion(request.requestId)}
      >
        {visibleColumns.expand && (
          <td>
            {isExpanded ? '−' : '+'}
          </td>
        )}
        {visibleColumns.method && (
          <td>
            {request.method}
          </td>
        )}
        {visibleColumns.status && (
          <td>
            {request.statusCode || '-'}
          </td>
        )}
        {visibleColumns.type && (
          <td>
            {request.resourceType}
          </td>
        )}
        {visibleColumns.priority && (
          <td className={styles.priorityCell}>
            <span>
              {getPriorityIcon(request.priority)}
              {request.priority || '-'}
            </span>
          </td>
        )}
        {visibleColumns.url && (
          <td>
            <a href={request.url} target="_blank" rel="noopener noreferrer">
              {truncateUrl(request.url)}
            </a>
          </td>
        )}
        {visibleColumns.connectionNumber && (
          <td>
            {request.connectionNumber || '-'}
          </td>
        )}
        {visibleColumns.requestNumber && (
          <td>
            {request.requestNumberOnConnection || '-'}
          </td>
        )}
        {visibleColumns.startTime && (
          <td>
            {formatDuration(request.timing.startOffset)}
          </td>
        )}
        {visibleColumns.queueTime && (
          <td className={getConnectionClass(request?.timing?.queueTime ||0)}>
            <div>
              {formatDuration(request.timing.queueTime)}
              {showQueueAnalysis && request.queueAnalysis && (
                <span 
                  title={request.queueAnalysis.description}
                >
                  {getQueueAnalysisIcon(request.queueAnalysis)}
                </span>
              )}
            </div>
          </td>
        )}
        
        {/* DNS Time */}
        {visibleColumns.dns && (
          <td >
            {request.timing.dnsStart !== undefined && request.timing.dnsEnd !== undefined && request.timing.dnsStart >= 0 && request.timing.dnsEnd >= 0
              ? formatDuration((request.timing.dnsEnd || 0) - (request.timing.dnsStart || 0))
              : <span>cached</span>
            }
          </td>
        )}
        
        {/* Connection Time */}
        {visibleColumns.connection && (
          <td className={getConnectionClass((request.timing.connectEnd || 0) - (request.timing.connectStart || 0))}>
            {request.timing.connectStart !== undefined && request.timing.connectEnd !== undefined
             && request.timing.connectStart >= 0 && request.timing.connectEnd >= 0
              ? <span >
                  {formatDuration((request.timing.connectEnd || 0) - (request.timing.connectStart || 0))}
                </span>
              : <span>
                  {request.connectionReused ? 'reused' : 'cached'}
                </span>
            }
          </td>
        )}
        
        {visibleColumns.serverLatency && (
          <td className={`${getServerLatencyClass(request.timing.serverLatency)}`}>
            {formatDuration(request.timing.serverLatency)}
          </td>
        )}
        
        {visibleColumns.duration && (
          <td className={getDurationClass(request.timing.duration)}>
            {formatDuration(request.timing.duration)}
          </td>
        )}
        
        {/* Total Response Time */}
        {visibleColumns.totalResponseTime && (
          <td className={`${getTotalResponseTimeClass(request.timing.totalResponseTime)}`}>
            {formatDuration(request.timing.totalResponseTime)}
          </td>
        )}
        
        {/* Data Rate */}
        {visibleColumns.dataRate && (
          <td className={`${getDataRateClass(request.encodedDataLength, request.contentLength, request.timing.duration)}`}>
            {formatDataRate(request.encodedDataLength, request.contentLength, request.timing.duration)}
          </td>
        )}
        
        {visibleColumns.size && (
          <td className={`${getSizeClass(request.encodedDataLength)}`}>
            {formatSize(request.encodedDataLength)}
          </td>
        )}
        
        {visibleColumns.contentLength && (
          <td className={`${getSizeClass(request.contentLength)}`}>
            {request.contentLength ? formatSize(request.contentLength) : '-'}
          </td>
        )}
        
        {visibleColumns.protocol && (
          <td className={getProtocolClass(request.protocol)}>
            {request.protocol || '-'}
          </td>
        )}
        
        {visibleColumns.cdn && (
          <td
          title={request.cdnAnalysis ? 
            `${getCDNDisplayName(request.cdnAnalysis.provider)} ${request.cdnAnalysis.isEdge ? '(Edge)' : '(Origin)'} - ${request.cdnAnalysis.detectionMethod}` : 
            'No CDN detected'}
          >
            {request.cdnAnalysis ? getCDNIcon(request.cdnAnalysis) : '-'}
          </td>
        )}
        
        {visibleColumns.cache && (
          <td>
            {request.fromCache ? '💾' : request.connectionReused ? '🔄' : '🌐'}
          </td>
        )}
      </tr>
      
      {/* Expanded Row Details */}
      {isExpanded && <RequestRowDetails request={request} visibleColumns={visibleColumns} />}
    </>
  )
}

export default RequestRowSummary