import React from 'react'
import RequestRowSummary from './RequestRowSummary'
import ScreenshotRow from './ScreenshotRow'
import { Tooltip } from '../shared/Tooltip'
import { TooltipType } from '../shared/tooltipDefinitions'
import styles from './RequestsTable.module.css'
import type { HTTPRequest, ScreenshotEvent } from './types/httpRequest'

interface RequestsTableProps {
  // Data
  httpRequests: HTTPRequest[]
  showScreenshots: boolean
  paginatedTimelineEntries: Array<{
    type: 'request' | 'screenshot'
    timestamp: number
    data: HTTPRequest | ScreenshotEvent
  }>
  paginatedRequests: HTTPRequest[]
  
  // Display options
  showQueueAnalysis: boolean
  visibleColumns: Record<string, boolean>
  
  // Row expansion state
  expandedRows: Set<string>
  onToggleRowExpansion: (requestId: string) => void
}

const RequestsTable: React.FC<RequestsTableProps> = ({
  httpRequests,
  showScreenshots,
  paginatedTimelineEntries,
  paginatedRequests,
  showQueueAnalysis,
  visibleColumns,
  expandedRows,
  onToggleRowExpansion
}) => {
  return (
    <>
      {/* Requests Table */}
      <div className={styles.tableContainer}>
        <table className={styles.table}>
          <thead className={styles.tableHeader}>
            <tr>
              {visibleColumns.expand && (
                <th className={`${styles.tableHeaderCell} ${styles.center} ${styles.expandColumn}`}>
                  <Tooltip type={TooltipType.EXPAND_ROW}>
                    Expand
                  </Tooltip>
                </th>
              )}
              {visibleColumns.method && (
                <th className={`${styles.tableHeaderCell} ${styles.left}`}>
                  <Tooltip type={TooltipType.HTTP_METHOD}>
                    Method
                  </Tooltip>
                </th>
              )}
              {visibleColumns.status && (
                <th className={`${styles.tableHeaderCell} ${styles.center}`}>
                  <Tooltip type={TooltipType.HTTP_STATUS}>
                    Status
                  </Tooltip>
                </th>
              )}
              {visibleColumns.type && (
                <th className={`${styles.tableHeaderCell} ${styles.left}`}>
                  <Tooltip type={TooltipType.RESOURCE_TYPE}>
                    Type
                  </Tooltip>
                </th>
              )}
              {visibleColumns.priority && (
                <th className={`${styles.tableHeaderCell} ${styles.center}`}>
                  <Tooltip type={TooltipType.REQUEST_PRIORITY}>
                    Priority
                  </Tooltip>
                </th>
              )}
              {visibleColumns.url && (
                <th className={`${styles.tableHeaderCell} ${styles.left}`}>
                  <Tooltip type={TooltipType.REQUEST_URL}>
                    URL
                  </Tooltip>
                </th>
              )}
              {visibleColumns.connectionNumber && (
                <th className={`${styles.tableHeaderCell} ${styles.center}`}>
                  <Tooltip type={TooltipType.CONNECTION_NUMBER}>
                    Connection #
                  </Tooltip>
                </th>
              )}
              {visibleColumns.requestNumber && (
                <th className={`${styles.tableHeaderCell} ${styles.center}`}>
                  <Tooltip type={TooltipType.REQUEST_NUMBER}>
                    Request #
                  </Tooltip>
                </th>
              )}
              {visibleColumns.startTime && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.START_TIME}>
                    Start Time
                  </Tooltip>
                </th>
              )}
              {visibleColumns.queueTime && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.QUEUE_TIME}>
                    Queue Time
                  </Tooltip>
                </th>
              )}
              {visibleColumns.dns && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.DNS_TIME}>
                    DNS
                  </Tooltip>
                </th>
              )}
              {visibleColumns.connection && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.CONNECTION_TIME}>
                    Connection
                  </Tooltip>
                </th>
              )}
              {visibleColumns.serverLatency && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.SERVER_LATENCY}>
                    Server Latency
                  </Tooltip>
                </th>
              )}
              {visibleColumns.duration && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.REQUEST_DURATION}>
                    Duration
                  </Tooltip>
                </th>
              )}
              {visibleColumns.totalResponseTime && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.TOTAL_RESPONSE_TIME}>
                    Total Response Time
                  </Tooltip>
                </th>
              )}
              {visibleColumns.dataRate && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.DATA_RATE}>
                    Data Rate
                  </Tooltip>
                </th>
              )}
              {visibleColumns.size && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.TRANSFER_SIZE}>
                    Size
                  </Tooltip>
                </th>
              )}
              {visibleColumns.contentLength && (
                <th className={`${styles.tableHeaderCell} ${styles.right}`}>
                  <Tooltip type={TooltipType.CONTENT_LENGTH}>
                    Content-Length
                  </Tooltip>
                </th>
              )}
              {visibleColumns.protocol && (
                <th className={`${styles.tableHeaderCell} ${styles.center}`}>
                  <Tooltip type={TooltipType.HTTP_PROTOCOL}>
                    Protocol
                  </Tooltip>
                </th>
              )}
              {visibleColumns.cdn && (
                <th className={`${styles.tableHeaderCell} ${styles.center}`}>
                  <Tooltip type={TooltipType.CDN_DETECTION}>
                    CDN
                  </Tooltip>
                </th>
              )}
              {visibleColumns.cache && (
                <th className={`${styles.tableHeaderCell} ${styles.center}`}>
                  <Tooltip type={TooltipType.CACHE_STATUS}>
                    Cache
                  </Tooltip>
                </th>
              )}
            </tr>
          </thead>
          <tbody>
            {(showScreenshots ? paginatedTimelineEntries : paginatedRequests.map(req => ({ type: 'request' as const, timestamp: req.timing.start, data: req }))).map((entry) => {
              if (entry.type === 'screenshot') {
                const screenshot = entry.data as ScreenshotEvent
                const firstRequestTime = httpRequests.length > 0 ? httpRequests[0].timing.start : 0
                
                return (
                  <ScreenshotRow
                    key={`screenshot-${screenshot.index}`}
                    screenshot={screenshot}
                    firstRequestTime={firstRequestTime}
                  />
                )
              }
              
              const request = entry.data as HTTPRequest
              const isExpanded = expandedRows.has(request.requestId)
              
              return (
                <RequestRowSummary
                  key={request.requestId}
                  request={request}
                  showQueueAnalysis={showQueueAnalysis}
                  isExpanded={isExpanded}
                  onToggleRowExpansion={onToggleRowExpansion}
                  visibleColumns={visibleColumns}
                />
              )
            })}
          </tbody>
        </table>
      </div>

      {/* No Results Message */}
      {(showScreenshots ? paginatedTimelineEntries.length === 0 : paginatedRequests.length === 0) && (
        <div className={styles.noResults}>
          {showScreenshots ? 
            'No timeline entries found matching the current filters' : 
            'No HTTP requests found matching the current filters'}
        </div>
      )}
    </>
  )
}

export default RequestsTable