@extends('layout.app')

@push('styles')
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
    <link rel="stylesheet" href="https://unpkg.com/xterm/css/xterm.css" />
    <style>
        .monitoring-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .system-card {
            background: white;
            padding: 24px;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .system-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .card-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }

        .card-icon {
            margin-right: 12px;
            color: #4338ca;
            font-size: 28px !important;
        }

        .card-title {
            font-size: 0.9em;
            color: #6b7280;
            margin: 0;
            font-weight: 500;
        }

        .card-value {
            font-size: 2em;
            font-weight: 600;
            margin: 0;
            color: #111827;
        }

        .card-subtitle {
            font-size: 0.9em;
            color: #6b7280;
            margin-top: 8px;
        }

        .progress-bar {
            height: 6px;
            background: #e5e7eb;
            border-radius: 3px;
            margin-top: 15px;
            overflow: hidden;
        }

        .progress-value {
            height: 100%;
            background: #4338ca;
            transition: width 0.3s ease;
        }

        .terminal-container {
            background: white;
            padding: 16px;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
            min-height: 400px;
        }

        .terminal-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e5e7eb;
        }

        #terminal {
            min-height: 350px;
        }

        .terminal-credentials {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
        }

        .terminal-credentials input {
            height: 40px;
        }

        .terminal-credentials .hint {
            font-size: 0.8em;
            color: #6b7280;
            margin-top: 4px;
        }

        .connect-btn {
            background: #4338ca;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.2s;
        }

        .connect-btn:hover {
            background: #3730a3;
        }

        .connect-btn:disabled {
            background: #6b7280;
            cursor: not-allowed;
        }
    </style>
@endpush

@section('content')
    <div class="mx-auto" style="width: 85%;">
        <div class="row">
            <div class="col-12">
                <!-- System Monitoring Cards -->
                <div class="monitoring-cards">
                    <div class="system-card">
                        <div class="card-header">
                            <span class="material-icons card-icon">memory</span>
                            <h3 class="card-title">CPU Usage</h3>
                        </div>
                        <p class="card-value" id="cpu-usage">0%</p>
                        <div class="progress-bar">
                            <div class="progress-value" id="cpu-bar" style="width: 0%"></div>
                        </div>
                    </div>

                    <div class="system-card">
                        <div class="card-header">
                            <span class="material-icons card-icon">storage</span>
                            <h3 class="card-title">Memory Usage</h3>
                        </div>
                        <p class="card-value" id="memory-usage">0%</p>
                        <p class="card-subtitle" id="memory-details">0 GB / 0 GB</p>
                        <div class="progress-bar">
                            <div class="progress-value" id="memory-bar" style="width: 0%"></div>
                        </div>
                    </div>

                    <div class="system-card">
                        <div class="card-header">
                            <span class="material-icons card-icon">timer</span>
                            <h3 class="card-title">Uptime</h3>
                        </div>
                        <p class="card-value" id="uptime">0h 0m</p>
                    </div>

                    <div class="system-card">
                        <div class="card-header">
                            <span class="material-icons card-icon">dns</span>
                            <h3 class="card-title">System Info</h3>
                        </div>
                        <p class="card-value" id="hostname">-</p>
                        <p class="card-subtitle" id="platform">-</p>
                    </div>
                </div>

                <!-- Terminal Section -->
                <div class="terminal-credentials">
                    <div class="row g-3">
                        <div class="col-md-2">
                            <input type="text" class="form-control" id="host" placeholder="Host" autocomplete="off"
                                spellcheck="false" value="{{ $server_ip }}" />
                        </div>
                        <div class="col-md-2">
                            <input type="text" class="form-control" id="port" placeholder="Port (22)"
                                autocomplete="off" spellcheck="false" />
                        </div>
                        <div class="col-md-2">
                            <input type="text" class="form-control" id="username" placeholder="Username"
                                autocomplete="off" spellcheck="false" />
                        </div>
                        <div class="col-md-2">
                            <input type="password" class="form-control" id="password" placeholder="Password"
                                autocomplete="new-password" spellcheck="false" />
                        </div>
                        <div class="col-md-2">
                            <input type="text" class="form-control" id="initialPath" placeholder="Initial Path"
                                autocomplete="off" spellcheck="false" value="{{ $base_path }}" />
                        </div>
                        <div class="col-md-2">
                            <button onclick="connect()" class="btn connect-btn w-100">Connect</button>
                        </div>
                    </div>
                    <p class="hint mt-2">Default credentials will be used if fields are left empty</p>
                </div>

                <div class="terminal-container">
                    <div class="terminal-header">
                        <h5 class="mb-0"><i class="material-icons align-middle me-2">terminal</i> Terminal</h5>
                    </div>
                    <div id="terminal"></div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('js')
    <script src="https://unpkg.com/xterm/lib/xterm.js"></script>
    <script>
        const term = new Terminal({
            cursorBlink: true,
            fontSize: 14,
            lineHeight: 1.2,
            fontFamily: 'Menlo, Monaco, "Courier New", monospace',
            cols: 140,
            rows: 30,
            allowProposedApi: true,
        });

        term.open(document.getElementById("terminal"));
        let ws = null;

        function loadSavedCredentials() {
            const saved = localStorage.getItem("ssh-credentials");
            if (saved) {
                const creds = JSON.parse(saved);
                document.getElementById("host").value = creds.host || "";
                document.getElementById("port").value = creds.port || "22";
                document.getElementById("username").value = creds.username || "";
                document.getElementById("password").value = creds.password || "";
                document.getElementById("initialPath").value =
                    creds.initialPath || "";
            }
        }

        function saveCredentials(host, port, username, password, initialPath) {
            localStorage.setItem(
                "ssh-credentials",
                JSON.stringify({
                    host,
                    port,
                    username,
                    password,
                    initialPath,
                })
            );
        }

        function connect(isRetry = false) {
            const connectButton = document.querySelector(".connect-btn");
            if (connectButton.disabled && !isRetry) return;

            const host = document.getElementById("host").value.trim();
            const port = document.getElementById("port").value.trim();
            const username = document.getElementById("username").value.trim();
            const password = document.getElementById("password").value.trim();
            const initialPath = document.getElementById("initialPath").value.trim();

            // Only save to localStorage if values are provided
            const credsToSave = {};
            if (host) credsToSave.host = host;
            if (port) credsToSave.port = port;
            if (username) credsToSave.username = username;
            if (password) credsToSave.password = password;
            if (initialPath) credsToSave.initialPath = initialPath;

            if (Object.keys(credsToSave).length > 0) {
                localStorage.setItem("ssh-credentials", JSON.stringify(credsToSave));
            }

            connectButton.disabled = true;
            connectButton.textContent = "Connecting...";

            if (ws) {
                ws.close();
                ws = null;
            }

            ws = new WebSocket(`wss://{{ $ssh_server_ip }}`);

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

            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                if (data.type === "systemInfo") {
                    updateSystemInfo(data.data);
                } else if (data.type === "data") {
                    term.write(data.message);
                } else if (data.type === "status") {
                    term.writeln(`\r\n${data.message}\r\n`);
                    if (data.message === "Connected successfully") {
                        connectButton.textContent = "Connected";
                        connectButton.disabled = true;
                    }
                } else if (data.type === "error") {
                    term.writeln(`\r\n\x1b[31m${data.message}\x1b[0m\r\n`);
                    if (data.message.includes("Could not reach server")) {
                        connectButton.textContent = "Retry";
                        connectButton.className = "connect-btn retry";
                        connectButton.disabled = false;
                        connectButton.onclick = () => connect(true);
                    } else {
                        connectButton.textContent = "Connect";
                        connectButton.className = "connect-btn";
                        connectButton.disabled = false;
                        connectButton.onclick = () => connect(false);
                    }
                }
            };

            term.onData((data) => {
                if (ws && ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify({
                        type: "data",
                        data
                    }));
                }
            });

            ws.onclose = () => {
                term.writeln("\r\n\x1b[31mConnection closed\x1b[0m\r\n");
                if (!connectButton.className.includes("retry")) {
                    connectButton.disabled = false;
                    connectButton.textContent = "Connect";
                }
            };
        }

        function updateSystemInfo(info) {
            document.getElementById("cpu-usage").textContent = `${info.cpu}%`;
            document.getElementById("cpu-bar").style.width = `${info.cpu}%`;
            document.getElementById("memory-usage").textContent = `${info.memory}%`;
            document.getElementById("memory-bar").style.width = `${info.memory}%`;
            document.getElementById(
                "memory-details"
            ).textContent = `${info.memoryUsed} GB / ${info.totalMemory} GB`;
            const hours = Math.floor(info.uptime / 3600);
            const minutes = Math.floor((info.uptime % 3600) / 60);
            document.getElementById("uptime").textContent = `${hours}h ${minutes}m`;
            document.getElementById("hostname").textContent = info.hostname;
            document.getElementById("platform").textContent = info.platform;
        }

        //   loadSavedCredentials();
    </script>
@endpush
