import { useState, useMemo } from 'react'
import { useDatabaseTraceData } from '../../hooks/useDatabaseTraceData'
import { processJavaScriptEvents, calculateJavaScriptSummary } from './lib/javascriptProcessor'
import JavaScriptSummary from './JavaScriptSummary'
import JavaScriptEventsTable from './JavaScriptEventsTable'
import styles from './JavaScriptViewer.module.css'

interface JavaScriptViewerProps {
  traceId: string | null
}

const JavaScriptViewer: React.FC<JavaScriptViewerProps> = ({ traceId }) => {
  const { traceData, loading, error } = useDatabaseTraceData(traceId)
  
  // Column visibility state for the table
  const [visibleColumns] = useState(() => ({
    icon: true,
    eventType: true,
    duration: true,
    url: true,
    location: true,
    scriptType: true,
    streaming: true,
    startTime: false
  }))

  // Filter states
  const [eventTypeFilter, setEventTypeFilter] = useState<string>('all')
  const [searchTerm, setSearchTerm] = useState('')
  const [minDuration, setMinDuration] = useState<number>(0)

  const jsEvents = useMemo(() => {
    if (!traceData) return []
    return processJavaScriptEvents(traceData.traceEvents)
  }, [traceData])

  const filteredEvents = useMemo(() => {
    let events = jsEvents

    // Filter by event type
    if (eventTypeFilter !== 'all') {
      events = events.filter(event => event.name === eventTypeFilter)
    }

    // Filter by minimum duration (in milliseconds)
    if (minDuration > 0) {
      events = events.filter(event => event.timing.durationMs >= minDuration)
    }

    // Filter by search term
    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      events = events.filter(event =>
        event.url?.toLowerCase().includes(term) ||
        event.fileName?.toLowerCase().includes(term) ||
        event.name.toLowerCase().includes(term)
      )
    }

    return events
  }, [jsEvents, eventTypeFilter, minDuration, searchTerm])

  const summary = useMemo(() => {
    return calculateJavaScriptSummary(jsEvents)
  }, [jsEvents])

  // Extract unique event types for filter dropdown
  const eventTypes = useMemo(() => {
    const types = Array.from(new Set(jsEvents.map(event => event.name)))
    return types.sort()
  }, [jsEvents])

  if (loading) {
    return (
      <div className={styles.loading}>
        Loading JavaScript performance data...
      </div>
    )
  }

  if (error) {
    return (
      <div className={styles.error}>
        Error loading trace data: {error}
      </div>
    )
  }

  if (!traceData) {
    return (
      <div className={styles.noData}>
        No trace data available
      </div>
    )
  }

  return (
    <div className={styles.container}>
      <h2 className={styles.title}>JavaScript Performance Analysis</h2>
      
      {/* Summary Statistics */}
      <JavaScriptSummary summary={summary} />

      {/* Filters */}
      <div className={styles.filtersContainer}>
        <h3 className={styles.filtersTitle}>Filters</h3>
        <div className={styles.filters}>
          <div className={styles.filterGroup}>
            <label className={styles.filterLabel}>Event Type:</label>
            <select 
              value={eventTypeFilter} 
              onChange={(e) => setEventTypeFilter(e.target.value)}
              className={styles.filterSelect}
            >
              <option value="all">All Events</option>
              {eventTypes.map(type => (
                <option key={type} value={type}>{type}</option>
              ))}
            </select>
          </div>

          <div className={styles.filterGroup}>
            <label className={styles.filterLabel}>Min Duration (ms):</label>
            <input
              type="number"
              min="0"
              step="0.1"
              value={minDuration}
              onChange={(e) => setMinDuration(parseFloat(e.target.value) || 0)}
              className={styles.filterInput}
            />
          </div>

          <div className={styles.filterGroup}>
            <label className={styles.filterLabel}>Search:</label>
            <input
              type="text"
              placeholder="Search URLs, files, or event types..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className={styles.filterInput}
            />
          </div>
        </div>

        <div className={styles.resultsInfo}>
          Showing {filteredEvents.length} of {jsEvents.length} JavaScript events
        </div>
      </div>

      {/* Events Table */}
      <JavaScriptEventsTable 
        events={filteredEvents}
        visibleColumns={visibleColumns}
      />
    </div>
  )
}

export default JavaScriptViewer