import { useEffect, useRef } from 'react'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import 'xterm/css/xterm.css'

export function TerminalPage() {
  const containerRef = useRef<HTMLDivElement>(null)
  const terminalRef = useRef<Terminal | null>(null)

  useEffect(() => {
    if (!containerRef.current) return

    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const host = window.location.host
    const token = localStorage.getItem('token')
    const wsUrl = `${protocol}//${host}/api/v1/terminal/ws${token ? `?token=${token}` : ''}`

    const term = new Terminal({
      cursorBlink: true,
      theme: {
        background: '#1e1e1e',
        foreground: '#d4d4d4',
      },
    })
    const fitAddon = new FitAddon()
    term.loadAddon(fitAddon)
    term.open(containerRef.current)
    fitAddon.fit()

    const ws = new WebSocket(wsUrl)
    ws.binaryType = 'arraybuffer'

    ws.onopen = () => {
      term.writeln('YakPanel Terminal - Connected')
      term.writeln('')
    }

    ws.onmessage = (ev) => {
      if (typeof ev.data === 'string') {
        term.write(ev.data)
      } else {
        const decoder = new TextDecoder()
        term.write(decoder.decode(ev.data))
      }
    }

    ws.onclose = () => {
      term.writeln('\r\n\r\nDisconnected from server.')
    }

    ws.onerror = () => {
      term.writeln('\r\n\r\nConnection error.')
    }

    term.onData((data) => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send(data)
      }
    })

    const resize = () => fitAddon.fit()
    window.addEventListener('resize', resize)

    terminalRef.current = term

    return () => {
      window.removeEventListener('resize', resize)
      ws.close()
      term.dispose()
      terminalRef.current = null
    }
  }, [])

  return (
    <div>
      <h1 className="text-2xl font-bold mb-4 text-gray-800 dark:text-white">Terminal</h1>
      <div
        ref={containerRef}
        className="rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700"
        style={{ height: 'calc(100vh - 200px)', minHeight: 400 }}
      />
    </div>
  )
}
