import React, { useEffect, useState, useCallback, useRef } from 'react'
import styles from './LogsPage.module.css'

interface LogEntry {
  line: string
  service?: string
}

interface LogsResponse {
  deployment_type: string
  service: string
  logs: LogEntry[]
  count: number
  error?: string
  message?: string
}

type ComponentType = 'router' | 'envoy' | 'dashboard' | 'all'

const COMPONENT_OPTIONS: Array<{ value: ComponentType; label: string }> = [
  { value: 'router', label: 'Router' },
  { value: 'envoy', label: 'Envoy' },
  { value: 'dashboard', label: 'Dashboard' },
  { value: 'all', label: 'All services' },
]

const LogsPage: React.FC = () => {
  const [selectedComponent, setSelectedComponent] = useState<ComponentType>('all')
  const [logs, setLogs] = useState<LogEntry[]>([])
  const [deploymentType, setDeploymentType] = useState<string>('detecting...')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [message, setMessage] = useState<string | null>(null)
  const [autoScroll, setAutoScroll] = useState(true)
  const [autoRefresh, setAutoRefresh] = useState(false)
  const [lines, setLines] = useState(100)
  const logsContainerRef = useRef<HTMLDivElement>(null)

  const fetchLogs = useCallback(async () => {
    try {
      const response = await fetch(`/api/logs?component=${selectedComponent}&lines=${lines}`)
      if (!response.ok) {
        throw new Error(`Failed to fetch logs: ${response.statusText}`)
      }
      const data: LogsResponse = await response.json()
      setLogs(data.logs || [])
      setDeploymentType(data.deployment_type)
      setError(data.error || null)
      setMessage(data.message || null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error')
    } finally {
      setLoading(false)
    }
  }, [selectedComponent, lines])

  useEffect(() => {
    setLoading(true)
    fetchLogs()

    if (autoRefresh) {
      const interval = setInterval(fetchLogs, 5000)
      return () => clearInterval(interval)
    }
  }, [fetchLogs, autoRefresh])

  useEffect(() => {
    if (autoScroll && logsContainerRef.current) {
      logsContainerRef.current.scrollTop = logsContainerRef.current.scrollHeight
    }
  }, [logs, autoScroll])

  const formatDeploymentType = (type: string) => {
    if (type === 'none') return 'Not detected'
    if (type === 'detecting...') return 'Detecting'
    return type
      .split(/[-_\s]+/)
      .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
      .join(' ')
  }

  const getLogLevel = (line: string): string => {
    const lowerLine = line.toLowerCase()
    if (lowerLine.includes('"level":"error"') || lowerLine.includes('[error]')) return 'error'
    if (lowerLine.includes('"level":"warn"') || lowerLine.includes('[warn]')) return 'warn'
    if (lowerLine.includes('"level":"info"') || lowerLine.includes('[info]')) return 'info'
    if (lowerLine.includes('"level":"debug"') || lowerLine.includes('[debug]')) return 'debug'
    return ''
  }

  const activeComponentLabel =
    COMPONENT_OPTIONS.find((option) => option.value === selectedComponent)?.label || 'All services'

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <span className={styles.eyebrow}>Operations</span>
          <h1 className={styles.title}>System Logs</h1>
          <p className={styles.subtitle}>View live output from vLLM Semantic Router services and runtime helpers.</p>
        </div>
        <div className={styles.headerRight}>
          <span className={styles.headerMeta}>Active stream: {activeComponentLabel}</span>
          <span className={styles.headerMeta}>Deployment: {formatDeploymentType(deploymentType)}</span>
        </div>
      </div>

      <div className={styles.summaryGrid}>
        <article className={styles.summaryCard}>
          <span className={styles.summaryLabel}>Deployment</span>
          <strong className={styles.summaryValue}>{formatDeploymentType(deploymentType)}</strong>
          <span className={styles.summaryHint}>Resolved from the active runtime environment.</span>
        </article>
        <article className={styles.summaryCard}>
          <span className={styles.summaryLabel}>Selected source</span>
          <strong className={styles.summaryValue}>{activeComponentLabel}</strong>
          <span className={styles.summaryHint}>Switch sources without changing the log viewport width.</span>
        </article>
        <article className={styles.summaryCard}>
          <span className={styles.summaryLabel}>Entries loaded</span>
          <strong className={styles.summaryValue}>{logs.length}</strong>
          <span className={styles.summaryHint}>Showing the latest {lines} lines per request.</span>
        </article>
      </div>

      <section className={styles.controlPanel}>
        <div className={styles.controlPanelHeader}>
          <div>
            <h2 className={styles.panelTitle}>Stream controls</h2>
            <p className={styles.panelSubtitle}>Tune source selection, tail length, and live refresh behavior.</p>
          </div>
        </div>

        <div className={styles.controls}>
          <div className={styles.serviceSelector}>
            {COMPONENT_OPTIONS.map((option) => (
              <button
                key={option.value}
                className={`${styles.serviceButton} ${selectedComponent === option.value ? styles.active : ''}`}
                onClick={() => setSelectedComponent(option.value)}
              >
                {option.label}
              </button>
            ))}
          </div>

          <div className={styles.controlsRight}>
            <div className={styles.linesSelector}>
              <label htmlFor="logs-lines">Lines</label>
              <select
                id="logs-lines"
                value={lines}
                onChange={(e) => setLines(Number(e.target.value))}
                className={styles.linesSelect}
              >
                <option value={50}>50</option>
                <option value={100}>100</option>
                <option value={200}>200</option>
                <option value={500}>500</option>
              </select>
            </div>

            <label className={styles.toggle}>
              <input
                type="checkbox"
                checked={autoRefresh}
                onChange={(e) => setAutoRefresh(e.target.checked)}
              />
              <span>Auto-refresh</span>
            </label>

            <label className={styles.toggle}>
              <input
                type="checkbox"
                checked={autoScroll}
                onChange={(e) => setAutoScroll(e.target.checked)}
              />
              <span>Auto-scroll</span>
            </label>

            <button onClick={fetchLogs} className={styles.refreshButton}>
              Refresh
            </button>
          </div>
        </div>
      </section>

      {error && (
        <div className={styles.error}>
          <span className={styles.messageLabel}>Log error</span>
          <span>{error}</span>
        </div>
      )}

      {message && !error && (
        <div className={styles.info}>
          <span className={styles.messageLabel}>Notice</span>
          <span>{message}</span>
        </div>
      )}

      <div className={styles.logsSection}>
        <div className={styles.logsHeader}>
          <div className={styles.logsHeaderText}>
            <span className={styles.logsEyebrow}>Live stream</span>
            <span className={styles.logsTitle}>{activeComponentLabel}</span>
          </div>
          <span className={styles.logsCount}>{logs.length} entries</span>
        </div>

        <div ref={logsContainerRef} className={styles.logsContainer}>
          {loading && logs.length === 0 ? (
            <div className={styles.loadingLogs}>
              <div className={styles.spinner}></div>
              <span>Fetching logs...</span>
            </div>
          ) : logs.length === 0 ? (
            <div className={styles.noLogs}>
              <p className={styles.noLogsTitle}>No logs available</p>
              {deploymentType === 'none' && (
                <p className={styles.noLogsHint}>
                  No running deployment detected. Start the router first.
                </p>
              )}
            </div>
          ) : (
            <div className={styles.logsList}>
              {logs.map((log, index) => {
                const level = getLogLevel(log.line)
                return (
                  <div 
                    key={index} 
                    className={`${styles.logEntry} ${level ? styles[`level${level.charAt(0).toUpperCase() + level.slice(1)}`] : ''}`}
                  >
                    <span className={styles.logLine}>{log.line}</span>
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default LogsPage
