import { useState, useEffect, useRef } from 'react'
import { FileText, Save, RefreshCw, AlertTriangle, Check, X } from 'lucide-react'
import { getOpenTTDConfig, saveOpenTTDConfig } from '../api'

export default function OpenTTDConfigEditor({ token }) {
  const [content, setContent] = useState('')
  const [originalContent, setOriginalContent] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState(null)
  const [success, setSuccess] = useState(null)
  const [hasChanges, setHasChanges] = useState(false)
  const textareaRef = useRef(null)
  const highlightRef = useRef(null)

  useEffect(() => {
    loadConfig()
  }, [token])

  useEffect(() => {
    setHasChanges(content !== originalContent)
  }, [content, originalContent])

  const handleScroll = () => {
    if (highlightRef.current && textareaRef.current) {
      highlightRef.current.scrollTop = textareaRef.current.scrollTop
      highlightRef.current.scrollLeft = textareaRef.current.scrollLeft
    }
  }

  async function loadConfig() {
    setLoading(true)
    setError(null)
    try {
      const data = await getOpenTTDConfig(token)
      setContent(data.content)
      setOriginalContent(data.content)
    } catch (err) {
      setError('Fehler beim Laden der Config: ' + err.message)
    } finally {
      setLoading(false)
    }
  }

  async function handleSave() {
    if (!hasChanges) return

    setSaving(true)
    setError(null)
    setSuccess(null)
    try {
      await saveOpenTTDConfig(token, content)
      setOriginalContent(content)
      setSuccess('Config gespeichert! Server-Neustart erforderlich.')
      setTimeout(() => setSuccess(null), 5000)
    } catch (err) {
      setError('Fehler beim Speichern: ' + err.message)
    } finally {
      setSaving(false)
    }
  }

  function handleDiscard() {
    setContent(originalContent)
    setError(null)
    setSuccess(null)
  }

  function highlightSyntax(text) {
    if (!text) return ''

    const lines = text.split('\n')

    return lines.map((line) => {
      let highlighted = line
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')

      // Section headers [section]
      if (line.trim().startsWith('[') && line.trim().endsWith(']')) {
        highlighted = `<span class="text-purple-400 font-bold">${highlighted}</span>`
      }
      // Comments (;)
      else if (line.trim().startsWith(';')) {
        highlighted = `<span class="text-emerald-500">${highlighted}</span>`
      }
      // key = value
      else if (line.includes('=')) {
        const idx = line.indexOf('=')
        const key = highlighted.substring(0, idx)
        const value = highlighted.substring(idx + 1)

        // Color numbers first (with placeholders), then booleans
        // This prevents the regex from matching numbers in CSS class names like "text-orange-400"
        let coloredValue = value
          .replace(/\b(\d+)\b/g, '%%%NUM_START%%%$1%%%NUM_END%%%')
          .replace(/\b(true|false)\b/gi, '<span class="text-orange-400">$1</span>')
          .replace(/%%%NUM_START%%%/g, '<span class="text-cyan-400">')
          .replace(/%%%NUM_END%%%/g, '</span>')

        highlighted = `<span class="text-blue-400">${key}</span>=<span class="text-amber-300">${coloredValue}</span>`
      }

      return highlighted
    }).join('\n')
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <RefreshCw className="w-6 h-6 animate-spin text-gray-400" />
        <span className="ml-2 text-gray-400">Lade Config...</span>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 text-sm text-gray-400">
          <FileText className="w-4 h-4" />
          <span>openttd.cfg - Server-Einstellungen</span>
        </div>
        <button
          onClick={loadConfig}
          disabled={loading}
          className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
          title="Neu laden"
        >
          <RefreshCw className={"w-5 h-5 " + (loading ? 'animate-spin' : '')} />
        </button>
      </div>

      {/* Error/Success messages */}
      {error && (
        <div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400">
          <AlertTriangle className="w-5 h-5 flex-shrink-0" />
          <span>{error}</span>
        </div>
      )}

      {success && (
        <div className="flex items-center gap-2 p-3 bg-green-500/10 border border-green-500/30 rounded-lg text-green-400">
          <Check className="w-5 h-5 flex-shrink-0" />
          <span>{success}</span>
        </div>
      )}

      {/* Editor */}
      <div className="relative h-[500px] rounded-lg overflow-hidden border border-gray-700">
        <pre
          ref={highlightRef}
          className="absolute inset-0 p-4 m-0 text-sm font-mono bg-gray-900 text-gray-100 overflow-auto pointer-events-none whitespace-pre-wrap break-words"
          style={{ wordBreak: 'break-word' }}
          aria-hidden="true"
          dangerouslySetInnerHTML={{ __html: highlightSyntax(content) + '\n' }}
        />

        <textarea
          ref={textareaRef}
          value={content}
          onChange={(e) => setContent(e.target.value)}
          onScroll={handleScroll}
          className="absolute inset-0 w-full h-full p-4 text-sm font-mono bg-transparent text-transparent caret-white resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-inset"
          spellCheck={false}
          disabled={loading}
          style={{ caretColor: 'white' }}
        />

        {hasChanges && (
          <div className="absolute top-2 right-2 px-2 py-1 bg-yellow-500/20 text-yellow-400 text-xs rounded z-10">
            Ungespeichert
          </div>
        )}
      </div>

      {/* Actions */}
      <div className="flex items-center justify-end gap-3">
        {hasChanges && (
          <button
            onClick={handleDiscard}
            className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
          >
            <X className="w-4 h-4" />
            Verwerfen
          </button>
        )}

        <button
          onClick={handleSave}
          disabled={!hasChanges || saving}
          className={"flex items-center gap-2 px-4 py-2 rounded-lg transition-colors " +
            (hasChanges && !saving
              ? 'bg-green-600 hover:bg-green-500 text-white border-2 border-green-400'
              : 'bg-gray-700 text-gray-500 cursor-not-allowed border-2 border-gray-600'
            )}
        >
          {saving ? (
            <>
              <RefreshCw className="w-4 h-4 animate-spin" />
              Speichern...
            </>
          ) : (
            <>
              <Save className="w-4 h-4" />
              Speichern
            </>
          )}
        </button>
      </div>

      {/* Legend */}
      <div className="mt-4 p-4 bg-gray-800/50 rounded-lg border border-gray-700">
        <h4 className="text-sm font-medium text-gray-300 mb-2">Legende</h4>
        <div className="flex flex-wrap gap-4 text-xs">
          <div className="flex items-center gap-2">
            <span className="w-3 h-3 rounded bg-purple-400"></span>
            <span className="text-gray-400">Sektion</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="w-3 h-3 rounded bg-emerald-500"></span>
            <span className="text-gray-400">Kommentare</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="w-3 h-3 rounded bg-blue-400"></span>
            <span className="text-gray-400">Einstellung</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="w-3 h-3 rounded bg-amber-300"></span>
            <span className="text-gray-400">Wert</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="w-3 h-3 rounded bg-orange-400"></span>
            <span className="text-gray-400">Boolean</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="w-3 h-3 rounded bg-cyan-400"></span>
            <span className="text-gray-400">Zahlen</span>
          </div>
        </div>
        <p className="text-xs text-gray-500 mt-3">Änderungen werden erst nach Server-Neustart aktiv. Ein Backup wird automatisch erstellt.</p>
      </div>
    </div>
  )
}
