import React from 'react'
import type { HTTPRequest, CallFrame } from './types/httpRequest'
import styles from './InitiatorView.module.css'

interface InitiatorViewProps {
  request: HTTPRequest
}

const InitiatorView: React.FC<InitiatorViewProps> = ({ request }) => {
  if (!request.initiator) {
    return (
      <div className={styles.noInitiator}>
        No initiator information available
      </div>
    )
  }

  const { initiator } = request
  const hasStack = initiator.stack && initiator.stack.callFrames.length > 0

  const getInitiatorTypeIcon = (type: string) => {
    switch (type) {
      case 'parser': return '📄'
      case 'script': return '📜'
      case 'preload': return '⚡'
      default: return '❓'
    }
  }

  const getFetchTypeIcon = (fetchType?: string) => {
    switch (fetchType) {
      case 'script': return '🔧'
      case 'link': return '🔗'
      case 'fetch': return '📡'
      case 'xhr': return '📤'
      case 'img': return '🖼️'
      default: return '📋'
    }
  }

  const truncateUrl = (url: string, maxLength: number = 60) => {
    if (url.length <= maxLength) return url
    const start = url.substring(0, 20)
    const end = url.substring(url.length - 35)
    return `${start}...${end}`
  }

  const formatLocation = (lineNumber?: number, columnNumber?: number) => {
    if (lineNumber !== undefined && columnNumber !== undefined) {
      return `${lineNumber}:${columnNumber}`
    }
    if (lineNumber !== undefined) {
      return `${lineNumber}`
    }
    return '-'
  }

  const renderCallFrame = (frame: CallFrame, index: number) => (
    <div key={index} className={styles.callFrame}>
      <div className={styles.frameIndex}>{index + 1}</div>
      <div className={styles.frameDetails}>
        <div className={styles.frameFunction}>
          {frame.functionName || '(anonymous)'}
        </div>
        <div className={styles.frameLocation}>
          <a 
            href={frame.url} 
            target="_blank" 
            rel="noopener noreferrer"
            className={styles.frameUrl}
            title={frame.url}
          >
            {truncateUrl(frame.url)}
          </a>
          <span className={styles.framePosition}>
            @ {formatLocation(frame.lineNumber, frame.columnNumber)}
          </span>
        </div>
      </div>
    </div>
  )

  return (
    <div className={styles.initiatorContainer}>
      <div className={styles.initiatorHeader}>
        <h4 className={styles.title}>Request Initiator</h4>
      </div>

      {/* Initiator Type Information */}
      <div className={styles.initiatorInfo}>
        <div className={styles.infoRow}>
          <span className={styles.infoLabel}>Type:</span>
          <span className={styles.infoValue}>
            {getInitiatorTypeIcon(initiator.type)} {initiator.type}
          </span>
        </div>
        
        {initiator.fetchType && (
          <div className={styles.infoRow}>
            <span className={styles.infoLabel}>Fetch Type:</span>
            <span className={styles.infoValue}>
              {getFetchTypeIcon(initiator.fetchType)} {initiator.fetchType}
            </span>
          </div>
        )}
      </div>

      {/* Parser-initiated requests */}
      {initiator.type === 'parser' && initiator.url && (
        <div className={styles.parserInfo}>
          <h5 className={styles.sectionTitle}>📄 Document Parser</h5>
          <div className={styles.parserDetails}>
            <div className={styles.parserUrl}>
              <a 
                href={initiator.url} 
                target="_blank" 
                rel="noopener noreferrer"
                className={styles.urlLink}
                title={initiator.url}
              >
                {truncateUrl(initiator.url)}
              </a>
            </div>
            {(initiator.lineNumber || initiator.columnNumber) && (
              <div className={styles.parserLocation}>
                Line {formatLocation(initiator.lineNumber, initiator.columnNumber)}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Script-initiated requests with call stack */}
      {initiator.type === 'script' && hasStack && (
        <div className={styles.stackInfo}>
          <h5 className={styles.sectionTitle}>📜 Call Stack</h5>
          <div className={styles.callStack}>
            {initiator.stack!.callFrames.map((frame, index) => 
              renderCallFrame(frame, index)
            )}
          </div>
        </div>
      )}

      {/* Other types without detailed information */}
      {!hasStack && initiator.type !== 'parser' && (
        <div className={styles.basicInfo}>
          <div className={styles.basicInfoText}>
            This request was initiated by {initiator.type}
            {initiator.fetchType && ` using ${initiator.fetchType}`}
          </div>
        </div>
      )}
    </div>
  )
}

export default InitiatorView