import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Terminal, Wifi, WifiOff, X, Plus, ChevronDown } from 'lucide-react';

// Serveurs SSH prédéfinis
const PRESET_SERVERS = [
  {
    id: 'recette',
    label: 'Recette (78.138.58.109)',
    host: '78.138.58.109',
    port: 22,
    username: 'root',
  },
  {
    id: 'production',
    label: 'Production (180.149.196.138)',
    host: '180.149.196.138',
    port: 22,
    username: 'root',
  },
];

export default function TerminalPage() {
  const terminalRef = useRef(null);
  const xtermRef = useRef(null);
  const fitAddonRef = useRef(null);
  const wsRef = useRef(null);
  const [connected, setConnected] = useState(false);
  const [connecting, setConnecting] = useState(false);
  const [xtermLoaded, setXtermLoaded] = useState(false);

  // Formulaire de connexion
  const [form, setForm] = useState({
    preset: 'recette',
    host: '78.138.58.109',
    port: 22,
    username: 'root',
    password: '',
  });
  const [showForm, setShowForm] = useState(true);
  const [error, setError] = useState('');

  // Charger xterm.js dynamiquement depuis CDN
  useEffect(() => {
    const loadXterm = async () => {
      if (window.Terminal) {
        setXtermLoaded(true);
        return;
      }

      // Charger le CSS xterm
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = 'https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css';
      document.head.appendChild(link);

      // Charger xterm.js
      await loadScript('https://cdn.jsdelivr.net/npm/xterm@5.3.0/lib/xterm.js');
      await loadScript('https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.8.0/lib/xterm-addon-fit.js');

      setXtermLoaded(true);
    };

    loadXterm();
  }, []);

  const loadScript = (src) => {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = src;
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });
  };

  // Initialiser xterm quand il est chargé et que le terminal est visible
  useEffect(() => {
    if (!xtermLoaded || !terminalRef.current || xtermRef.current) return;

    const term = new window.Terminal({
      cursorBlink: true,
      fontSize: 14,
      fontFamily: '"Cascadia Code", "Fira Code", "JetBrains Mono", monospace',
      theme: {
        background: '#0d1117',
        foreground: '#e6edf3',
        cursor: '#58a6ff',
        cursorAccent: '#0d1117',
        black: '#484f58',
        red: '#ff7b72',
        green: '#3fb950',
        yellow: '#d29922',
        blue: '#58a6ff',
        magenta: '#bc8cff',
        cyan: '#39c5cf',
        white: '#b1bac4',
        brightBlack: '#6e7681',
        brightRed: '#ffa198',
        brightGreen: '#56d364',
        brightYellow: '#e3b341',
        brightBlue: '#79c0ff',
        brightMagenta: '#d2a8ff',
        brightCyan: '#56d4dd',
        brightWhite: '#f0f6fc',
      },
      scrollback: 1000,
      allowProposedApi: true,
    });

    const fitAddon = new window.FitAddon.FitAddon();
    term.loadAddon(fitAddon);
    term.open(terminalRef.current);
    fitAddon.fit();

    xtermRef.current = term;
    fitAddonRef.current = fitAddon;

    term.writeln('\x1b[1;34m╔══════════════════════════════════════════════════╗\x1b[0m');
    term.writeln('\x1b[1;34m║     Terminal SSH — Dashboard Recette Santinova   ║\x1b[0m');
    term.writeln('\x1b[1;34m╚══════════════════════════════════════════════════╝\x1b[0m');
    term.writeln('');
    term.writeln('\x1b[90mSélectionnez un serveur et connectez-vous pour démarrer.\x1b[0m');
    term.writeln('');

    // Gérer la saisie utilisateur
    term.onData((data) => {
      if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
        wsRef.current.send(JSON.stringify({ type: 'input', data }));
      }
    });

    // Gérer le redimensionnement
    const resizeObserver = new ResizeObserver(() => {
      if (fitAddonRef.current) {
        fitAddonRef.current.fit();
        if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
          wsRef.current.send(JSON.stringify({
            type: 'resize',
            rows: term.rows,
            cols: term.cols,
          }));
        }
      }
    });

    if (terminalRef.current) {
      resizeObserver.observe(terminalRef.current);
    }

    return () => {
      resizeObserver.disconnect();
    };
  }, [xtermLoaded]);

  const handlePresetChange = (presetId) => {
    const preset = PRESET_SERVERS.find(s => s.id === presetId);
    if (preset) {
      setForm(prev => ({
        ...prev,
        preset: presetId,
        host: preset.host,
        port: preset.port,
        username: preset.username,
      }));
    } else {
      setForm(prev => ({ ...prev, preset: 'custom' }));
    }
  };

  const handleConnect = useCallback(() => {
    if (!form.host || !form.username || !form.password) {
      setError('Hôte, utilisateur et mot de passe sont requis');
      return;
    }

    setError('');
    setConnecting(true);
    setShowForm(false);

    const token = localStorage.getItem('dashboard_token');
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${wsProtocol}//${window.location.host}/ws-ssh?token=${token}`;

    const ws = new WebSocket(wsUrl);
    wsRef.current = ws;

    ws.onopen = () => {
      ws.send(JSON.stringify({
        type: 'connect',
        host: form.host,
        port: parseInt(form.port),
        username: form.username,
        password: form.password,
      }));
    };

    ws.onmessage = (event) => {
      try {
        const msg = JSON.parse(event.data);

        switch (msg.type) {
          case 'status':
            if (xtermRef.current) {
              xtermRef.current.writeln(`\x1b[33m${msg.message}\x1b[0m`);
            }
            break;

          case 'connected':
            setConnected(true);
            setConnecting(false);
            if (xtermRef.current) {
              xtermRef.current.writeln(`\x1b[32m✓ ${msg.message}\x1b[0m`);
              xtermRef.current.writeln('');
              xtermRef.current.focus();
            }
            break;

          case 'output':
            if (xtermRef.current) {
              const data = atob(msg.data);
              xtermRef.current.write(data);
            }
            break;

          case 'disconnected':
            setConnected(false);
            setConnecting(false);
            if (xtermRef.current) {
              xtermRef.current.writeln('');
              xtermRef.current.writeln(`\x1b[33m⚠ ${msg.message}\x1b[0m`);
            }
            break;

          case 'error':
            setConnected(false);
            setConnecting(false);
            setError(msg.message);
            if (xtermRef.current) {
              xtermRef.current.writeln(`\x1b[31m✗ Erreur: ${msg.message}\x1b[0m`);
            }
            setShowForm(true);
            break;
        }
      } catch (err) {
        console.error('Erreur parsing message SSH:', err);
      }
    };

    ws.onclose = () => {
      setConnected(false);
      setConnecting(false);
    };

    ws.onerror = () => {
      setConnected(false);
      setConnecting(false);
      setError('Erreur de connexion WebSocket');
      setShowForm(true);
    };
  }, [form]);

  const handleDisconnect = () => {
    if (wsRef.current) {
      wsRef.current.send(JSON.stringify({ type: 'disconnect' }));
      wsRef.current.close();
      wsRef.current = null;
    }
    setConnected(false);
    setConnecting(false);
    setShowForm(true);
    if (xtermRef.current) {
      xtermRef.current.writeln('');
      xtermRef.current.writeln('\x1b[90mDéconnecté. Configurez une nouvelle connexion.\x1b[0m');
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-white flex items-center gap-3">
            <Terminal className="w-7 h-7 text-emerald-400" />
            Terminal SSH
          </h2>
          <p className="text-gray-400 mt-1">
            Connexion SSH sécurisée aux serveurs de l'infrastructure
          </p>
        </div>
        <div className="flex items-center gap-2">
          {connected ? (
            <>
              <span className="flex items-center gap-2 text-emerald-400 text-sm">
                <Wifi className="w-4 h-4" />
                Connecté à {form.host}
              </span>
              <button
                onClick={handleDisconnect}
                className="flex items-center gap-2 px-3 py-1.5 bg-red-600/20 text-red-400 border border-red-500/30 rounded-lg text-sm hover:bg-red-600/30 transition-colors"
              >
                <X className="w-4 h-4" />
                Déconnecter
              </button>
            </>
          ) : connecting ? (
            <span className="flex items-center gap-2 text-yellow-400 text-sm">
              <div className="w-4 h-4 border-2 border-yellow-400 border-t-transparent rounded-full animate-spin" />
              Connexion en cours...
            </span>
          ) : (
            <span className="flex items-center gap-2 text-gray-500 text-sm">
              <WifiOff className="w-4 h-4" />
              Non connecté
            </span>
          )}
        </div>
      </div>

      {/* Formulaire de connexion */}
      {showForm && (
        <div className="bg-dark-800 border border-dark-600 rounded-xl p-6">
          <h3 className="text-white font-semibold mb-4 flex items-center gap-2">
            <Plus className="w-4 h-4 text-primary-400" />
            Nouvelle connexion SSH
          </h3>

          {error && (
            <div className="mb-4 px-4 py-3 bg-red-900/30 border border-red-500/40 rounded-lg text-red-400 text-sm">
              {error}
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Serveur prédéfini */}
            <div className="md:col-span-2">
              <label className="block text-sm text-gray-400 mb-1">Serveur prédéfini</label>
              <div className="relative">
                <select
                  value={form.preset}
                  onChange={(e) => handlePresetChange(e.target.value)}
                  className="w-full bg-dark-700 border border-dark-500 text-white rounded-lg px-3 py-2.5 text-sm appearance-none focus:outline-none focus:border-primary-500"
                >
                  {PRESET_SERVERS.map(s => (
                    <option key={s.id} value={s.id}>{s.label}</option>
                  ))}
                  <option value="custom">Serveur personnalisé...</option>
                </select>
                <ChevronDown className="absolute right-3 top-3 w-4 h-4 text-gray-400 pointer-events-none" />
              </div>
            </div>

            {/* Hôte */}
            <div>
              <label className="block text-sm text-gray-400 mb-1">Hôte / IP</label>
              <input
                type="text"
                value={form.host}
                onChange={(e) => setForm(prev => ({ ...prev, host: e.target.value, preset: 'custom' }))}
                placeholder="192.168.1.1"
                className="w-full bg-dark-700 border border-dark-500 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-primary-500"
              />
            </div>

            {/* Port */}
            <div>
              <label className="block text-sm text-gray-400 mb-1">Port SSH</label>
              <input
                type="number"
                value={form.port}
                onChange={(e) => setForm(prev => ({ ...prev, port: e.target.value }))}
                placeholder="22"
                className="w-full bg-dark-700 border border-dark-500 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-primary-500"
              />
            </div>

            {/* Utilisateur */}
            <div>
              <label className="block text-sm text-gray-400 mb-1">Utilisateur</label>
              <input
                type="text"
                value={form.username}
                onChange={(e) => setForm(prev => ({ ...prev, username: e.target.value }))}
                placeholder="root"
                className="w-full bg-dark-700 border border-dark-500 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-primary-500"
              />
            </div>

            {/* Mot de passe */}
            <div>
              <label className="block text-sm text-gray-400 mb-1">Mot de passe</label>
              <input
                type="password"
                value={form.password}
                onChange={(e) => setForm(prev => ({ ...prev, password: e.target.value }))}
                placeholder="••••••••"
                onKeyDown={(e) => e.key === 'Enter' && handleConnect()}
                className="w-full bg-dark-700 border border-dark-500 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-primary-500"
              />
            </div>
          </div>

          <div className="mt-4 flex justify-end">
            <button
              onClick={handleConnect}
              disabled={connecting}
              className="flex items-center gap-2 px-5 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
            >
              <Terminal className="w-4 h-4" />
              Se connecter
            </button>
          </div>
        </div>
      )}

      {/* Terminal xterm.js */}
      <div className="bg-dark-900 border border-dark-600 rounded-xl overflow-hidden">
        {/* Barre de titre style terminal */}
        <div className="flex items-center gap-2 px-4 py-3 bg-dark-800 border-b border-dark-600">
          <div className="w-3 h-3 rounded-full bg-red-500/70" />
          <div className="w-3 h-3 rounded-full bg-yellow-500/70" />
          <div className="w-3 h-3 rounded-full bg-green-500/70" />
          <span className="ml-2 text-xs text-gray-500 font-mono">
            {connected ? `${form.username}@${form.host}` : 'terminal — non connecté'}
          </span>
          {connected && !showForm && (
            <button
              onClick={() => setShowForm(!showForm)}
              className="ml-auto text-xs text-gray-500 hover:text-gray-300 transition-colors"
            >
              {showForm ? 'Masquer' : 'Nouvelle connexion'}
            </button>
          )}
        </div>

        {/* Zone du terminal */}
        <div
          ref={terminalRef}
          style={{ height: '500px', padding: '8px', backgroundColor: '#0d1117' }}
        />
      </div>

      {!xtermLoaded && (
        <div className="text-center text-gray-500 text-sm py-4">
          Chargement du terminal...
        </div>
      )}
    </div>
  );
}
