"""
MineConnect Client - Simple Web GUI

Provides a lightweight web interface for controlling tunnels.
Runs a local HTTP server and opens a browser.
"""

import webbrowser
import threading
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, unquote
from .cli_client import MineConnectClient


class GUIRequestHandler(BaseHTTPRequestHandler):
    """HTTP request handler for the GUI."""
    
    client: MineConnectClient = None
    
    def log_message(self, format, *args):
        """Suppress default logging."""
        pass
    
    def do_GET(self):
        """Handle GET requests."""
        path = urlparse(self.path).path
        
        if path == "/" or path == "/index.html":
            self.send_html()
        elif path == "/api/status":
            self.send_json(self.client.get_status())
        else:
            self.send_response(404)
            self.end_headers()
    
    def do_POST(self):
        """Handle POST requests."""
        path = urlparse(self.path).path
        
        if path == "/api/connect":
            content_length = int(self.headers.get('Content-Length', 0))
            body = self.rfile.read(content_length).decode('utf-8')
            data = json.loads(body) if body else {}
            tunnel = data.get('tunnel', 'both')
            
            if tunnel == 'java':
                self.client.connect_java()
            elif tunnel == 'bedrock':
                self.client.connect_bedrock()
            else:
                self.client.connect_both()
            
            self.send_json({"success": True})
        
        elif path == "/api/disconnect":
            content_length = int(self.headers.get('Content-Length', 0))
            body = self.rfile.read(content_length).decode('utf-8')
            data = json.loads(body) if body else {}
            tunnel = data.get('tunnel', 'all')
            
            if tunnel == 'java':
                self.client.disconnect_java()
            elif tunnel == 'bedrock':
                self.client.disconnect_bedrock()
            else:
                self.client.disconnect()
            
            self.send_json({"success": True})
        else:
            self.send_response(404)
            self.end_headers()
    
    def send_json(self, data):
        """Send JSON response."""
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode('utf-8'))
    
    def send_html(self):
        """Send the HTML interface."""
        html = get_html_template(self.client.domain)
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=utf-8')
        self.end_headers()
        self.wfile.write(html.encode('utf-8'))


def get_html_template(domain: str) -> str:
    """Generate the HTML interface."""
    return f'''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MineConnect Client</title>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{
            font-family: system-ui, -apple-system, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }}
        .container {{
            background: white;
            border-radius: 20px;
            padding: 40px;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }}
        h1 {{
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
        }}
        .domain {{
            color: #667eea;
            font-size: 14px;
            margin-bottom: 30px;
        }}
        .tunnel {{
            background: #f7f7f7;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
        }}
        .tunnel-header {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }}
        .tunnel-name {{
            font-weight: 600;
            font-size: 18px;
            color: #333;
        }}
        .status {{
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }}
        .status.disconnected {{ background: #e0e0e0; color: #666; }}
        .status.connecting {{ background: #fff3cd; color: #856404; }}
        .status.connected {{ background: #d4edda; color: #155724; }}
        .status.reconnecting {{ background: #fff3cd; color: #856404; }}
        .status.error {{ background: #f8d7da; color: #721c24; }}
        .buttons {{
            display: flex;
            gap: 10px;
        }}
        button {{
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }}
        button:hover {{ transform: translateY(-1px); }}
        button:active {{ transform: translateY(0); }}
        .btn-connect {{
            background: #667eea;
            color: white;
        }}
        .btn-connect:hover {{ background: #5568d3; }}
        .btn-disconnect {{
            background: #e0e0e0;
            color: #666;
        }}
        .btn-disconnect:hover {{ background: #d0d0d0; }}
        .all-buttons {{
            margin-top: 30px;
            display: flex;
            gap: 10px;
        }}
        .all-buttons button {{
            flex: 1;
            padding: 14px;
            font-size: 16px;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>🎮 MineConnect</h1>
        <div class="domain">Connected to: {domain}</div>
        
        <div id="java-tunnel" class="tunnel">
            <div class="tunnel-header">
                <span class="tunnel-name">Java Edition</span>
                <span class="status disconnected" id="java-status">disconnected</span>
            </div>
            <div class="buttons">
                <button class="btn-connect" onclick="connectJava()">Connect</button>
                <button class="btn-disconnect" onclick="disconnectJava()">Disconnect</button>
            </div>
        </div>
        
        <div id="bedrock-tunnel" class="tunnel">
            <div class="tunnel-header">
                <span class="tunnel-name">Bedrock Edition</span>
                <span class="status disconnected" id="bedrock-status">disconnected</span>
            </div>
            <div class="buttons">
                <button class="btn-connect" onclick="connectBedrock()">Connect</button>
                <button class="btn-disconnect" onclick="disconnectBedrock()">Disconnect</button>
            </div>
        </div>
        
        <div class="all-buttons">
            <button class="btn-connect" onclick="connectBoth()">Connect Both</button>
            <button class="btn-disconnect" onclick="disconnectAll()">Disconnect All</button>
        </div>
    </div>
    
    <script>
        function updateStatus() {{
            fetch('/api/status')
                .then(r => r.json())
                .then(data => {{
                    document.getElementById('java-status').className = 'status ' + data.java;
                    document.getElementById('java-status').textContent = data.java;
                    document.getElementById('bedrock-status').className = 'status ' + data.bedrock;
                    document.getElementById('bedrock-status').textContent = data.bedrock;
                }});
        }}
        
        function connectJava() {{
            fetch('/api/connect', {{
                method: 'POST',
                headers: {{'Content-Type': 'application/json'}},
                body: JSON.stringify({{tunnel: 'java'}})
            }});
        }}
        
        function connectBedrock() {{
            fetch('/api/connect', {{
                method: 'POST',
                headers: {{'Content-Type': 'application/json'}},
                body: JSON.stringify({{tunnel: 'bedrock'}})
            }});
        }}
        
        function connectBoth() {{
            fetch('/api/connect', {{
                method: 'POST',
                headers: {{'Content-Type': 'application/json'}},
                body: JSON.stringify({{tunnel: 'both'}})
            }});
        }}
        
        function disconnectJava() {{
            fetch('/api/disconnect', {{
                method: 'POST',
                headers: {{'Content-Type': 'application/json'}},
                body: JSON.stringify({{tunnel: 'java'}})
            }});
        }}
        
        function disconnectBedrock() {{
            fetch('/api/disconnect', {{
                method: 'POST',
                headers: {{'Content-Type': 'application/json'}},
                body: JSON.stringify({{tunnel: 'bedrock'}})
            }});
        }}
        
        function disconnectAll() {{
            fetch('/api/disconnect', {{
                method: 'POST',
                headers: {{'Content-Type': 'application/json'}},
                body: JSON.stringify({{tunnel: 'all'}})
            }});
        }}
        
        // Update status every second
        setInterval(updateStatus, 1000);
        updateStatus();
    </script>
</body>
</html>'''


def run_gui(domain: str = "ideadev.me", port: int = 8080):
    """
    Run the GUI server and open browser.
    
    Args:
        domain: Your server domain
        port: Local port for GUI server (default: 8080)
    """
    client = MineConnectClient(domain=domain)
    
    # Set client on handler class
    GUIRequestHandler.client = client
    
    # Start server
    server = HTTPServer(("127.0.0.1", port), GUIRequestHandler)
    server_thread = threading.Thread(target=server.serve_forever, daemon=True)
    server_thread.start()
    
    url = f"http://127.0.0.1:{port}"
    print(f"MineConnect GUI running at {url}")
    print("Press Ctrl+C to stop")
    
    # Open browser
    webbrowser.open(url)
    
    try:
        while True:
            import time
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n\nShutting down...")
        client.disconnect()
        server.shutdown()
        print("Stopped.")


def main():
    """Entry point for GUI mode."""
    import argparse
    parser = argparse.ArgumentParser(description="MineConnect Client GUI")
    parser.add_argument("--domain", default="ideadev.me", help="Your server domain")
    parser.add_argument("--port", type=int, default=8080, help="GUI server port")
    args = parser.parse_args()
    
    run_gui(domain=args.domain, port=args.port)


if __name__ == "__main__":
    main()
