import { useState, useRef, useEffect } from 'react'
import { X, Play, Loader, Terminal, Copy, Check } from 'lucide-react'
import api from '../api/client'
import { copyToClipboard } from '../utils/clipboard'

export default function ScriptModal({ agentId, agentName, onClose }) {
  const [script, setScript] = useState('#!/bin/bash\n\n')
  const [timeout, setTimeout_] = useState(60)
  const [running, setRunning] = useState(false)
  const [output, setOutput] = useState(null)
  const [error, setError] = useState(null)
  const [copied, setCopied] = useState(false)
  const outputRef = useRef(null)

  useEffect(() => {
    if (output !== null && outputRef.current) {
      outputRef.current.scrollTop = outputRef.current.scrollHeight
    }
  }, [output])

  const run = async () => {
    if (!script.trim()) return
    setRunning(true)
    setOutput(null)
    setError(null)
    try {
      const res = await api.execCommand(agentId, script, timeout)
      setOutput(res?.data?.output ?? res?.output ?? '(kein Output)')
    } catch (e) {
      setError(e.message)
      if (e.data?.output) setOutput(e.data.output)
    } finally {
      setRunning(false)
    }
  }

  const copyOutput = () => {
    if (output) {
      copyToClipboard(output)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm"
         onClick={onClose}>
      <div className="bg-gray-900 rounded-xl border border-gray-700 shadow-2xl flex flex-col"
           style={{ width: '80vw', maxWidth: '1000px', height: '80vh' }}
           onClick={e => e.stopPropagation()}>

        {/* Header */}
        <div className="flex items-center gap-3 px-5 py-3 border-b border-gray-700/60 bg-gray-800/50 rounded-t-xl">
          <Terminal className="w-4 h-4 text-orange-400" />
          <span className="text-sm font-mono text-gray-200">Script ausführen — <span className="text-orange-400">{agentName}</span></span>
          <div className="ml-auto flex items-center gap-3">
            <label className="flex items-center gap-2 text-xs text-gray-400">
              Timeout (s):
              <input type="number" value={timeout} onChange={e => setTimeout_(parseInt(e.target.value) || 60)}
                className="w-16 bg-gray-700 border border-gray-600 rounded px-2 py-1 text-white text-xs focus:outline-none focus:border-orange-500" />
            </label>
            <button onClick={run} disabled={running || !script.trim()}
              className="flex items-center gap-1.5 px-3 py-1.5 bg-orange-600 hover:bg-orange-700 disabled:bg-gray-700 disabled:text-gray-500 rounded text-sm text-white transition-colors">
              {running ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Läuft...</> : <><Play className="w-3.5 h-3.5" /> Ausführen</>}
            </button>
            <button onClick={onClose} className="text-gray-400 hover:text-white">
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Split: Editor + Output */}
        <div className="flex flex-1 min-h-0 divide-x divide-gray-700/60">
          {/* Script Editor */}
          <div className="flex flex-col flex-1 min-w-0">
            <div className="px-3 py-1.5 text-[10px] text-gray-500 uppercase tracking-wider bg-gray-800/30">Script</div>
            <textarea
              value={script}
              onChange={e => setScript(e.target.value)}
              spellCheck={false}
              className="flex-1 w-full bg-transparent text-sm font-mono text-gray-200 p-3 resize-none focus:outline-none"
              placeholder="#!/bin/bash&#10;&#10;# Script hier eingeben..."
            />
          </div>

          {/* Output */}
          <div className="flex flex-col flex-1 min-w-0">
            <div className="flex items-center px-3 py-1.5 bg-gray-800/30">
              <span className="text-[10px] text-gray-500 uppercase tracking-wider flex-1">Output</span>
              {output && (
                <button onClick={copyOutput} className="flex items-center gap-1 text-xs text-gray-500 hover:text-gray-300">
                  {copied ? <><Check className="w-3 h-3 text-green-400" /> Kopiert</> : <><Copy className="w-3 h-3" /> Kopieren</>}
                </button>
              )}
            </div>
            <div ref={outputRef}
              className="flex-1 overflow-auto p-3 font-mono text-xs leading-relaxed">
              {running && (
                <div className="flex items-center gap-2 text-yellow-400">
                  <Loader className="w-3 h-3 animate-spin" /> Script läuft...
                </div>
              )}
              {error && !running && (
                <div className="text-red-400 mb-2">Fehler: {error}</div>
              )}
              {output !== null && (
                <pre className={`whitespace-pre-wrap break-all ${error ? 'text-red-300' : 'text-green-300'}`}>
                  {output || '(kein Output)'}
                </pre>
              )}
              {output === null && !running && (
                <span className="text-gray-600">Noch kein Script ausgeführt</span>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
