import React, { useEffect, useRef, useState } from 'react'

interface LogLine {
  timestamp: string
  level: 'ERROR' | 'WARN' | 'INFO' | 'DEBUG'
  message: string
}

interface LogsViewerProps {
  pod: string
  namespace: string
}

export const LogsViewer: React.FC<LogsViewerProps> = ({ pod, namespace }) => {
  const logsRef = useRef<HTMLDivElement>(null)
  const [logs, setLogs] = useState<LogLine[]>([])
  const [autoScroll, setAutoScroll] = useState(true)
  useEffect(() => {
    const ws = new WebSocket(
      `/ws/logs?pod=${encodeURIComponent(pod)}&ns=${encodeURIComponent(namespace)}`
    )

    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        if (data.type === 'log') {
          setLogs((prev) => {
            const newLogs = [...prev, data.log]
            if (autoScroll && logsRef.current) {
              logsRef.current.scrollTop = logsRef.current.scrollHeight
            }
            return newLogs
          })
        }
      } catch (err) {
        console.error('Failed to parse log message:', err)
      }
    }

    ws.onclose = () => {
      console.log('Logs WebSocket closed')
    }

    return () => {
      ws.close()
    }
  }, [pod, namespace, autoScroll])

  const handleScroll = () => {
    if (logsRef.current) {
      const isAtBottom =
        logsRef.current.scrollTop + logsRef.current.clientHeight >=
        logsRef.current.scrollHeight - 10
      setAutoScroll(isAtBottom)
    }
  }

  const getColor = (level: string): string => {
    switch (level) {
      case 'ERROR':
        return '#ef6f6f'
      case 'WARN':
        return '#e8b54a'
      case 'DEBUG':
        return '#6b7280'
      default:
        return '#b9c6d8'
    }
  }

  return (
    <div
      ref={logsRef}
      onScroll={handleScroll}
      style={{
        height: '286px',
        overflow: 'auto',
        fontFamily: 'IBM Plex Mono, monospace',
        fontSize: '12px',
        lineHeight: '1.65',
        WebkitOverflowScrolling: 'touch',
      }}
    >
      {logs.map((line, index) => (
        <div
          key={index}
          style={{ color: getColor(line.level), whiteSpace: 'pre-wrap' }}
        >
          <span style={{ color: '#6b7280' }}>{line.timestamp} </span>
          {line.message}
        </div>
      ))}
      {logs.length === 0 && (
        <div style={{ color: '#888', textAlign: 'center', padding: '40px' }}>
          No logs yet...
        </div>
      )}
    </div>
  )
}
