import { json, type ActionFunctionArgs } from "@remix-run/node";
import { Form, useActionData, useLoaderData, useNavigation, useFetcher } from "@remix-run/react";
import { useState, useEffect, lazy, Suspense } from "react";
import ConnectDialog from "~/components/ConnectDialog";
import { useTheme } from "~/lib/ThemeContext";
import type { ThemeBrand, ThemeMode } from "~/lib/ThemeContext";

// Lazy load QR Scanner
const QRScanner = lazy(() => import("~/components/QRScanner"));

export async function loader() {
  try {
    const [configRes, wifiStatusRes, savedNetworksRes, cpuCoresRes, pluginsRes, sslInfoRes] = await Promise.all([
      fetch("http://localhost:8000/api/system/config"),
      fetch("http://localhost:8000/api/wifi/status"),
      fetch("http://localhost:8000/api/wifi/saved"),
      fetch("http://localhost:8000/api/system/cpu/cores"),
      fetch("http://localhost:8000/api/plugins/list"),
      fetch("http://localhost:8000/api/system/ssl/info"),
    ]);

    const config = await configRes.json();
    const wifiStatus = await wifiStatusRes.json();
    const savedNetworksData = await savedNetworksRes.json();
    const cpuCores = await cpuCoresRes.json();
    const plugins = pluginsRes.ok ? await pluginsRes.json() : [];
    const sslInfo = sslInfoRes.ok ? await sslInfoRes.json() : null;

    return json({
      config,
      wifiStatus,
      savedNetworks: savedNetworksData.networks || [],
      cpuCores,
      plugins,
      sslInfo
    });
  } catch (error) {
    return json({
      config: {
        pm3_device: "/dev/ttyACM0",
        session_timeout: 300,
        wifi_mode: "auto",
        ble_enabled: true,
        auth_enabled: false,
        https_enabled: false,
      },
      wifiStatus: {
        mode: "auto",
        interfaces: [],
        supports_dual: false,
        current_ssid: null,
        current_ip: null,
        ap_ssid: "raspi-webgui",
        ap_ip: "10.3.141.1",
      },
      savedNetworks: [],
      cpuCores: {
        total_cores: 4,
        online_cores: 4,
        configured_cores: null,
        configurable_cores: [1, 2, 3],
        pi_model: null
      },
      plugins: [],
      sslInfo: null,
    });
  }
}

export async function action({ request }: ActionFunctionArgs) {
  const formData = await request.formData();
  const action = formData.get("_action") as string;

  if (action === "restart") {
    try {
      await fetch("http://localhost:8000/api/system/restart", { method: "POST" });
      return json({ success: true, message: "System restart initiated" });
    } catch (error) {
      return json({ success: false, error: "Failed to restart system" });
    }
  }

  if (action === "shutdown") {
    try {
      await fetch("http://localhost:8000/api/system/shutdown", { method: "POST" });
      return json({ success: true, message: "System shutdown initiated" });
    } catch (error) {
      return json({ success: false, error: "Failed to shutdown system" });
    }
  }

  if (action === "set_wifi_mode") {
    const mode = formData.get("mode") as string;
    try {
      const response = await fetch("http://localhost:8000/api/wifi/mode", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ mode }),
      });
      const result = await response.json();
      return json({ success: true, message: `WiFi mode set to ${mode}` });
    } catch (error) {
      return json({ success: false, error: "Failed to set WiFi mode" });
    }
  }

  if (action === "scan_networks") {
    try {
      const response = await fetch("http://localhost:8000/api/wifi/scan");
      const networks = await response.json();
      return json({ success: true, networks, message: `Found ${networks.length} networks` });
    } catch (error) {
      return json({ success: false, error: "Failed to scan networks" });
    }
  }

  if (action === "connect_network") {
    const ssid = formData.get("ssid") as string;
    const password = formData.get("password") as string;
    const hidden = formData.get("hidden") === "true";

    try {
      const response = await fetch("http://localhost:8000/api/wifi/connect", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ssid, password: password || null, hidden }),
      });

      const result = await response.json();

      if (result.success) {
        return json({ success: true, message: `Connected to ${ssid}` });
      } else {
        return json({ success: false, error: "Failed to connect" });
      }
    } catch (error) {
      return json({ success: false, error: "Failed to connect to network" });
    }
  }

  if (action === "forget_network") {
    const ssid = formData.get("ssid") as string;

    try {
      const response = await fetch(`http://localhost:8000/api/wifi/saved/${encodeURIComponent(ssid)}`, {
        method: "DELETE",
      });

      const result = await response.json();

      if (result.success) {
        return json({ success: true, message: `Forgot network ${ssid}` });
      } else {
        return json({ success: false, error: "Failed to forget network" });
      }
    } catch (error) {
      return json({ success: false, error: "Failed to forget network" });
    }
  }

  if (action === "set_cpu_cores") {
    const numCores = parseInt(formData.get("num_cores") as string, 10);

    try {
      const response = await fetch("http://localhost:8000/api/system/cpu/cores", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          num_cores: numCores,
          persist: true,
          reboot: true
        }),
      });

      const result = await response.json();

      if (result.success) {
        return json({
          success: true,
          message: result.rebooting
            ? `CPU cores saved to ${numCores}. Rebooting...`
            : `CPU cores set to ${result.actual || numCores}`
        });
      } else {
        return json({ success: false, error: "Failed to set CPU cores" });
      }
    } catch (error) {
      return json({ success: false, error: "Failed to set CPU cores" });
    }
  }

  if (action === "toggle_https") {
    const enabled = formData.get("enabled") === "true";
    try {
      const response = await fetch("http://localhost:8000/api/system/ssl/toggle", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ enabled }),
      });
      const result = await response.json();
      if (result.success) {
        return json({ success: true, message: result.message });
      } else {
        return json({ success: false, error: "Failed to toggle HTTPS" });
      }
    } catch (error) {
      return json({ success: false, error: "Failed to toggle HTTPS" });
    }
  }

  if (action === "regenerate_ssl") {
    try {
      const response = await fetch("http://localhost:8000/api/system/ssl/regenerate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ reload_nginx: true }),
      });
      const result = await response.json();
      if (result.success) {
        return json({ success: true, message: "SSL certificate regenerated" });
      } else {
        return json({ success: false, error: "Failed to regenerate certificate" });
      }
    } catch (error) {
      return json({ success: false, error: "Failed to regenerate certificate" });
    }
  }

  if (action === "discover_plugins") {
    try {
      const response = await fetch("http://localhost:8000/api/plugins/discover");
      const result = await response.json();
      return json({ success: true, message: `Discovered ${result.count || 0} plugins` });
    } catch (error) {
      return json({ success: false, error: "Failed to discover plugins" });
    }
  }

  if (action === "enable_plugin") {
    const plugin_id = formData.get("plugin_id") as string;
    try {
      const response = await fetch("http://localhost:8000/api/plugins/enable", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plugin_id }),
      });
      if (response.ok) {
        return json({ success: true, message: `Plugin ${plugin_id} enabled` });
      } else {
        return json({ success: false, error: "Failed to enable plugin" });
      }
    } catch (error) {
      return json({ success: false, error: "Failed to enable plugin" });
    }
  }

  if (action === "disable_plugin") {
    const plugin_id = formData.get("plugin_id") as string;
    try {
      const response = await fetch("http://localhost:8000/api/plugins/disable", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plugin_id }),
      });
      if (response.ok) {
        return json({ success: true, message: `Plugin ${plugin_id} disabled` });
      } else {
        return json({ success: false, error: "Failed to disable plugin" });
      }
    } catch (error) {
      return json({ success: false, error: "Failed to disable plugin" });
    }
  }

  return json({ success: false, error: "Unknown action" });
}

export default function Settings() {
  const { config, wifiStatus, savedNetworks, cpuCores, plugins, sslInfo } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();
  const [activeSection, setActiveSection] = useState<"general" | "wifi" | "plugins" | "advanced" | "system" | "appearance">("general");
  const { brand, mode, setBrand, setMode, availableThemes } = useTheme();
  const [scannedNetworks, setScannedNetworks] = useState<any[]>([]);
  const [selectedNetwork, setSelectedNetwork] = useState<any>(null);
  const [showConnectDialog, setShowConnectDialog] = useState(false);
  const [showQRScanner, setShowQRScanner] = useState(false);
  const [selectedCores, setSelectedCores] = useState<number | null>(null);

  const isSubmitting = navigation.state === "submitting";

  // Reset selectedCores when loader data changes (after reboot)
  // Use configured_cores if available, otherwise online_cores
  const effectiveCores = cpuCores.configured_cores ?? cpuCores.online_cores;

  useEffect(() => {
    setSelectedCores(null);
  }, [effectiveCores]);

  useEffect(() => {
    if (actionData && "networks" in actionData) {
      setScannedNetworks(actionData.networks);
    }
  }, [actionData]);

  // Close dialog on successful connection
  useEffect(() => {
    if (actionData && actionData.success && showConnectDialog) {
      setShowConnectDialog(false);
      setSelectedNetwork(null);
    }
  }, [actionData, showConnectDialog]);

  const handleNetworkClick = (network: any) => {
    setSelectedNetwork(network);
    setShowConnectDialog(true);
  };

  const handleConnectHidden = () => {
    setSelectedNetwork(null);
    setShowConnectDialog(true);
  };

  const handleQRScan = (credentials: { ssid: string; password: string; security: string; hidden: boolean }) => {
    setShowQRScanner(false);
    // Pre-fill the connect dialog with scanned credentials
    setSelectedNetwork({
      ssid: credentials.ssid,
      encrypted: credentials.security !== "nopass",
      signal_strength: 0,
      _scannedPassword: credentials.password,  // Pass password to dialog
    });
    setShowConnectDialog(true);
  };

  const sections = [
    { id: "general", label: "General", icon: "⚙" },
    { id: "wifi", label: "Wi-Fi", icon: "📡" },
    { id: "plugins", label: "Plugins", icon: "🔌" },
    { id: "advanced", label: "Advanced", icon: "◈" },
    { id: "system", label: "System", icon: "⚡" },
    { id: "appearance", label: "Theme", icon: "◐" },
  ];

  const getSignalIcon = (strength: number) => {
    if (strength >= -50) return "▂▃▄▅▆";
    if (strength >= -60) return "▂▃▄▅";
    if (strength >= -70) return "▂▃▄";
    if (strength >= -80) return "▂▃";
    return "▂";
  };

  return (
    <div className="container">
      {actionData && "message" in actionData && (
        <div
          className="card"
          style={{
            marginBottom: "var(--space-4)",
            borderColor: actionData.success ? "var(--color-success)" : "var(--color-error)",
          }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: "var(--space-3)" }}>
            <span style={{ fontSize: "1.5rem" }}>
              {actionData.success ? "✓" : "✗"}
            </span>
            <span>{actionData.message || actionData.error}</span>
          </div>
        </div>
      )}

      {/* Settings Header + Section Tabs */}
      <div className="card" style={{ marginBottom: "var(--space-4)" }}>
        <h3 className="card-title">
          <span>⚙</span> Settings
        </h3>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(100px, 1fr))", gap: "var(--space-2)" }}>
          {sections.map((section) => (
            <button
              key={section.id}
              onClick={() => setActiveSection(section.id as any)}
              className={`btn ${activeSection === section.id ? "btn-primary" : "btn-secondary"}`}
              style={{ fontSize: "0.75rem" }}
            >
              <span>{section.icon}</span>
              <span>{section.label}</span>
            </button>
          ))}
        </div>
      </div>

      {/* General Settings */}
      {activeSection === "general" && (
        <div className="card">
          <h3 className="card-title">General Settings</h3>

          <div className="form-group">
            <label className="label">Session Timeout</label>
            <input
              type="number"
              className="input"
              defaultValue={config.session_timeout}
              disabled
            />
            <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
              Idle session timeout in seconds (currently: {Math.floor(config.session_timeout / 60)} minutes)
            </p>
          </div>

          <div className="form-group">
            <label className="label">Authentication</label>
            <div style={{ display: "flex", alignItems: "center", gap: "var(--space-3)" }}>
              <span className={`badge ${config.auth_enabled ? "badge-success" : "badge-info"}`}>
                {config.auth_enabled ? "Enabled" : "Disabled"}
              </span>
              <button className="btn btn-secondary" disabled>
                Configure
              </button>
            </div>
            <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
              Require password to access the web interface
            </p>
          </div>

          <div className="form-group">
            <label className="label">HTTPS</label>
            <div style={{ display: "flex", alignItems: "center", gap: "var(--space-3)" }}>
              <span className={`badge ${config.https_enabled ? "badge-success" : "badge-info"}`}>
                {config.https_enabled ? "Enabled" : "Disabled"}
              </span>
              <Form method="post" style={{ display: "inline" }}>
                <input type="hidden" name="_action" value="toggle_https" />
                <input type="hidden" name="enabled" value={config.https_enabled ? "false" : "true"} />
                <button className={`btn ${config.https_enabled ? "btn-secondary" : "btn-primary"}`} type="submit" disabled={isSubmitting}>
                  {config.https_enabled ? "Disable" : "Enable"}
                </button>
              </Form>
              <Form method="post" style={{ display: "inline" }}>
                <input type="hidden" name="_action" value="regenerate_ssl" />
                <button className="btn btn-secondary" type="submit" disabled={isSubmitting}>
                  Regenerate Cert
                </button>
              </Form>
            </div>
            <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
              Use self-signed certificate for secure connections
            </p>
            {sslInfo?.certificate_exists && (
              <div style={{ fontSize: "0.75rem", marginTop: "var(--space-2)", display: "flex", flexDirection: "column", gap: "2px" }}>
                <span className="text-muted">Expires: {sslInfo.not_after || "Unknown"}</span>
                {sslInfo.san && <span className="text-muted">SANs: {sslInfo.san.join(", ")}</span>}
                {sslInfo.fingerprint_sha256 && (
                  <span className="text-muted" style={{ fontFamily: "var(--font-mono)", fontSize: "0.65rem", wordBreak: "break-all" }}>
                    SHA256: {sslInfo.fingerprint_sha256}
                  </span>
                )}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Wi-Fi Settings */}
      {activeSection === "wifi" && (
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-4)" }}>
          {/* Current Status */}
          <div className="card">
            <h3 className="card-title">Current Status</h3>

            <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-3)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span className="text-secondary">Mode</span>
                <span className="badge badge-info" style={{ textTransform: "uppercase" }}>
                  {wifiStatus.mode}
                </span>
              </div>

              {wifiStatus.current_ssid && (
                <>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span className="text-secondary">Connected to</span>
                    <span className="text-primary">{wifiStatus.current_ssid}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span className="text-secondary">IP Address</span>
                    <span className="text-primary" style={{ fontFamily: "var(--font-mono)" }}>
                      {wifiStatus.current_ip}
                    </span>
                  </div>
                </>
              )}

              {wifiStatus.ap_ssid && (
                <>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span className="text-secondary">AP SSID</span>
                    <span className="text-primary">{wifiStatus.ap_ssid}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span className="text-secondary">AP IP</span>
                    <span className="text-primary" style={{ fontFamily: "var(--font-mono)" }}>
                      {wifiStatus.ap_ip}
                    </span>
                  </div>
                </>
              )}

              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span className="text-secondary">Interfaces</span>
                <span className="text-primary">{wifiStatus.interfaces.length}</span>
              </div>

              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span className="text-secondary">Dual Mode Support</span>
                <span className={`badge ${wifiStatus.supports_dual ? "badge-success" : "badge-info"}`}>
                  {wifiStatus.supports_dual ? "Available" : "Not Available"}
                </span>
              </div>
            </div>
          </div>

          {/* WiFi Interfaces */}
          {wifiStatus.interfaces.length > 0 && (
            <div className="card">
              <h3 className="card-title">Network Interfaces</h3>
              {wifiStatus.interfaces.map((iface: any) => (
                <div
                  key={iface.name}
                  style={{
                    marginBottom: "var(--space-3)",
                    padding: "var(--space-3)",
                    border: "1px solid var(--color-border)",
                    borderRadius: "var(--radius)",
                  }}
                >
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--space-2)" }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600 }}>
                      {iface.name} {iface.is_usb && <span className="badge badge-info">USB</span>}
                    </span>
                    <span className={`badge ${iface.is_up ? "badge-success" : "badge-error"}`}>
                      {iface.is_up ? "UP" : "DOWN"}
                    </span>
                  </div>
                  <div style={{ fontSize: "0.875rem", color: "var(--color-text-secondary)" }}>
                    <div>MAC: {iface.mac}</div>
                    {iface.ip_address && <div>IP: {iface.ip_address}</div>}
                    {iface.ssid && <div>SSID: {iface.ssid}</div>}
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Mode Selection */}
          <div className="card">
            <h3 className="card-title">WiFi Mode</h3>
            <p className="text-muted" style={{ fontSize: "0.875rem", marginBottom: "var(--space-4)" }}>
              Select how the Pi should handle WiFi connections
            </p>

            <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-2)" }}>
              <Form method="post">
                <input type="hidden" name="_action" value="set_wifi_mode" />
                <input type="hidden" name="mode" value="ap" />
                <button type="submit" className="btn btn-secondary" style={{ width: "100%", justifyContent: "flex-start" }}>
                  <span>📡</span>
                  <div style={{ textAlign: "left", flex: 1 }}>
                    <div>Access Point (AP)</div>
                    <div style={{ fontSize: "0.75rem", opacity: 0.7 }}>Host your own network</div>
                  </div>
                </button>
              </Form>

              <Form method="post">
                <input type="hidden" name="_action" value="set_wifi_mode" />
                <input type="hidden" name="mode" value="client" />
                <button type="submit" className="btn btn-secondary" style={{ width: "100%", justifyContent: "flex-start" }}>
                  <span>🌐</span>
                  <div style={{ textAlign: "left", flex: 1 }}>
                    <div>Client Mode</div>
                    <div style={{ fontSize: "0.75rem", opacity: 0.7 }}>Connect to existing WiFi</div>
                  </div>
                </button>
              </Form>

              {wifiStatus.supports_dual && (
                <Form method="post">
                  <input type="hidden" name="_action" value="set_wifi_mode" />
                  <input type="hidden" name="mode" value="dual" />
                  <button type="submit" className="btn btn-secondary" style={{ width: "100%", justifyContent: "flex-start" }}>
                    <span>🔀</span>
                    <div style={{ textAlign: "left", flex: 1 }}>
                      <div>Dual Mode</div>
                      <div style={{ fontSize: "0.75rem", opacity: 0.7 }}>AP + Client simultaneously</div>
                    </div>
                  </button>
                </Form>
              )}

              <Form method="post">
                <input type="hidden" name="_action" value="set_wifi_mode" />
                <input type="hidden" name="mode" value="auto" />
                <button type="submit" className="btn btn-secondary" style={{ width: "100%", justifyContent: "flex-start" }}>
                  <span>⚙</span>
                  <div style={{ textAlign: "left", flex: 1 }}>
                    <div>Auto Mode</div>
                    <div style={{ fontSize: "0.75rem", opacity: 0.7 }}>Automatically choose best mode</div>
                  </div>
                </button>
              </Form>
            </div>
          </div>

          {/* Scan Networks */}
          <div className="card">
            <h3 className="card-title">Available Networks</h3>

            <Form method="post">
              <input type="hidden" name="_action" value="scan_networks" />
              <button type="submit" className="btn btn-primary" disabled={isSubmitting}>
                {isSubmitting ? (
                  <>
                    <span className="spinner"></span>
                    <span>Scanning...</span>
                  </>
                ) : (
                  <>
                    <span>🔍</span>
                    <span>Scan for Networks</span>
                  </>
                )}
              </button>
            </Form>

            {scannedNetworks.length > 0 && (
              <div style={{ marginTop: "var(--space-4)" }}>
                {scannedNetworks.map((network: any, idx: number) => (
                  <div
                    key={`${network.bssid}-${idx}`}
                    style={{
                      padding: "var(--space-3)",
                      border: "1px solid var(--color-border)",
                      borderRadius: "var(--radius)",
                      marginBottom: "var(--space-2)",
                      cursor: "pointer",
                      transition: "all var(--transition-fast)",
                    }}
                    onClick={() => handleNetworkClick(network)}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.borderColor = "var(--color-primary)";
                      e.currentTarget.style.background = "var(--color-surface-hover)";
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.borderColor = "var(--color-border)";
                      e.currentTarget.style.background = "transparent";
                    }}
                  >
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <div>
                        <div style={{ fontWeight: 600 }}>
                          {network.ssid}
                          {network.encrypted && <span style={{ marginLeft: "var(--space-2)" }}>🔒</span>}
                        </div>
                        <div style={{ fontSize: "0.75rem", color: "var(--color-text-muted)" }}>
                          {network.frequency} MHz • {network.bssid}
                        </div>
                      </div>
                      <div style={{ display: "flex", alignItems: "center", gap: "var(--space-2)" }}>
                        <span style={{ fontSize: "0.75rem", fontFamily: "var(--font-mono)" }}>
                          {getSignalIcon(network.signal_strength)}
                        </span>
                        <span style={{ fontSize: "0.75rem", color: "var(--color-text-muted)" }}>
                          {network.signal_strength} dBm
                        </span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            <div style={{ marginTop: "var(--space-4)", display: "flex", gap: "var(--space-2)", justifyContent: "center", flexWrap: "wrap" }}>
              <button
                type="button"
                className="btn btn-primary"
                onClick={() => setShowQRScanner(true)}
              >
                <span>📷</span>
                <span>Scan WiFi QR</span>
              </button>
              <button
                type="button"
                className="btn btn-secondary"
                onClick={handleConnectHidden}
              >
                <span>➕</span>
                <span>Add Network</span>
              </button>
            </div>

            <p className="text-muted" style={{ fontSize: "0.875rem", marginTop: "var(--space-4)" }}>
              <strong>Note:</strong> Legacy WiFi management via RaspAP is still available at{" "}
              <a href="http://10.3.141.1" target="_blank" rel="noopener noreferrer">http://10.3.141.1</a>
            </p>
          </div>

          {/* Saved Networks */}
          {savedNetworks.length > 0 && (
            <div className="card">
              <h3 className="card-title">Saved Networks</h3>
              <p className="text-muted" style={{ fontSize: "0.875rem", marginBottom: "var(--space-4)" }}>
                Networks saved for auto-connect
              </p>

              {savedNetworks.map((network: any) => (
                <div
                  key={network.id}
                  style={{
                    padding: "var(--space-3)",
                    border: "1px solid var(--color-border)",
                    borderRadius: "var(--radius)",
                    marginBottom: "var(--space-2)",
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                  }}
                >
                  <div>
                    <div style={{ fontWeight: 600 }}>{network.ssid}</div>
                    <div style={{ fontSize: "0.75rem", color: "var(--color-text-muted)" }}>
                      {network.enabled ? "Enabled" : "Disabled"}
                    </div>
                  </div>
                  <Form method="post">
                    <input type="hidden" name="_action" value="forget_network" />
                    <input type="hidden" name="ssid" value={network.ssid} />
                    <button
                      type="submit"
                      className="btn btn-danger"
                      style={{ fontSize: "0.75rem", padding: "var(--space-2) var(--space-3)" }}
                      onClick={(e) => {
                        if (!confirm(`Forget network "${network.ssid}"?`)) {
                          e.preventDefault();
                        }
                      }}
                    >
                      <span>🗑</span>
                      <span>Forget</span>
                    </button>
                  </Form>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Connection Dialog */}
      {showConnectDialog && (
        <ConnectDialog
          network={selectedNetwork}
          onClose={() => {
            setShowConnectDialog(false);
            setSelectedNetwork(null);
          }}
          isSubmitting={isSubmitting}
        />
      )}

      {/* QR Scanner Modal */}
      {showQRScanner && (
        <Suspense
          fallback={
            <div
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                background: "rgba(var(--color-bg-rgb), 0.95)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                zIndex: 250,
              }}
            >
              <div style={{ textAlign: "center", color: "var(--color-text)" }}>
                <span className="spinner" style={{ marginBottom: "var(--space-2)" }}></span>
                <div>Loading scanner...</div>
              </div>
            </div>
          }
        >
          <QRScanner
            onScan={handleQRScan}
            onClose={() => setShowQRScanner(false)}
            onError={(err) => {
              console.error("QR Scanner error:", err);
              // Don't close immediately - let user see the error and dismiss manually
            }}
          />
        </Suspense>
      )}

      {/* Plugins Settings */}
      {activeSection === "plugins" && (
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-4)" }}>
          {/* Discover Plugins */}
          <div className="card">
            <h3 className="card-title">Installed Plugins</h3>
            <p className="text-muted" style={{ fontSize: "0.875rem", marginBottom: "var(--space-4)" }}>
              Manage plugins to extend Dangerous Pi functionality
            </p>

            <Form method="post">
              <input type="hidden" name="_action" value="discover_plugins" />
              <button type="submit" className="btn btn-secondary" disabled={isSubmitting}>
                {isSubmitting ? (
                  <>
                    <span className="spinner"></span>
                    <span>Discovering...</span>
                  </>
                ) : (
                  <>
                    <span>🔍</span>
                    <span>Discover Plugins</span>
                  </>
                )}
              </button>
            </Form>
          </div>

          {/* Plugin List */}
          {plugins.length > 0 ? (
            plugins.map((plugin: any) => (
              <div className="card" key={plugin.metadata.id}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: "var(--space-3)" }}>
                  <div style={{ flex: 1, minWidth: "200px" }}>
                    <h4 style={{ margin: 0, marginBottom: "var(--space-2)" }}>
                      {plugin.metadata.name}
                      <span
                        className={`badge ${plugin.status === "loaded" ? "badge-success" : plugin.status === "error" ? "badge-error" : "badge-info"}`}
                        style={{ marginLeft: "var(--space-2)", fontSize: "0.75rem" }}
                      >
                        {plugin.status}
                      </span>
                    </h4>
                    <p className="text-muted" style={{ fontSize: "0.875rem", marginBottom: "var(--space-2)" }}>
                      {plugin.metadata.description}
                    </p>
                    <div style={{ fontSize: "0.75rem", color: "var(--color-text-muted)", marginBottom: "var(--space-2)" }}>
                      <span>v{plugin.metadata.version}</span>
                      <span style={{ margin: "0 var(--space-2)" }}>•</span>
                      <span>by {plugin.metadata.author}</span>
                    </div>

                    {/* Permissions badges */}
                    {plugin.metadata.permissions && plugin.metadata.permissions.length > 0 && (
                      <div style={{ display: "flex", flexWrap: "wrap", gap: "var(--space-1)", marginTop: "var(--space-2)" }}>
                        {plugin.metadata.permissions.map((perm: string) => (
                          <span
                            key={perm}
                            className="badge badge-info"
                            style={{ fontSize: "0.625rem", padding: "2px 6px" }}
                          >
                            {perm}
                          </span>
                        ))}
                      </div>
                    )}

                    {/* Error message */}
                    {plugin.error_message && (
                      <div
                        style={{
                          marginTop: "var(--space-2)",
                          padding: "var(--space-2)",
                          background: "var(--color-error-bg)",
                          borderRadius: "var(--radius)",
                          fontSize: "0.75rem",
                          color: "var(--color-error)",
                        }}
                      >
                        {plugin.error_message}
                      </div>
                    )}
                  </div>

                  {/* Enable/Disable Toggle */}
                  <Form method="post">
                    <input type="hidden" name="_action" value={plugin.enabled ? "disable_plugin" : "enable_plugin"} />
                    <input type="hidden" name="plugin_id" value={plugin.metadata.id} />
                    <button
                      type="submit"
                      className={`btn ${plugin.enabled ? "btn-success" : "btn-secondary"}`}
                      disabled={isSubmitting}
                      style={{ minWidth: "100px" }}
                    >
                      {plugin.enabled ? "✓ Enabled" : "Disabled"}
                    </button>
                  </Form>
                </div>
              </div>
            ))
          ) : (
            <div className="card">
              <div style={{ textAlign: "center", padding: "var(--space-6)" }}>
                <div style={{ fontSize: "3rem", marginBottom: "var(--space-3)" }}>🔌</div>
                <h4 style={{ margin: 0, marginBottom: "var(--space-2)" }}>No Plugins Found</h4>
                <p className="text-muted" style={{ fontSize: "0.875rem" }}>
                  Place plugins in the <code style={{ fontFamily: "var(--font-mono)", background: "var(--color-surface)", padding: "2px 6px", borderRadius: "4px" }}>app/plugins/</code> directory
                </p>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Advanced Settings */}
      {activeSection === "advanced" && (
        <div className="card">
          <h3 className="card-title">Advanced Settings</h3>

          <div className="form-group">
            <label className="label">PM3 Device Path</label>
            <input
              type="text"
              className="input"
              defaultValue={config.pm3_device}
              disabled
              style={{ fontFamily: "var(--font-mono)" }}
            />
            <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
              Serial device path for Proxmark3
            </p>
          </div>

          <div className="form-group">
            <label className="label">BLE Notifications</label>
            <div style={{ display: "flex", alignItems: "center", gap: "var(--space-3)" }}>
              <span className={`badge ${config.ble_enabled ? "badge-success" : "badge-info"}`}>
                {config.ble_enabled ? "Enabled" : "Disabled"}
              </span>
              <button className="btn btn-secondary" disabled>
                Configure
              </button>
            </div>
            <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
              Send notifications via Bluetooth LE
            </p>
          </div>

          <div className="form-group">
            <label className="label">Automatic Updates</label>
            <div style={{ display: "flex", gap: "var(--space-2)" }}>
              <button className="btn btn-secondary" disabled>
                Check for Updates
              </button>
              <button className="btn btn-secondary" disabled>
                Auto-Update Settings
              </button>
            </div>
            <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
              Check GitHub for new Dangerous Pi releases
            </p>
          </div>
        </div>
      )}

      {/* Appearance */}
      {activeSection === "appearance" && (
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-4)" }}>
          <div className="card">
            <h3 className="card-title">Theme</h3>
            <div className="form-group">
              <label className="label">Brand</label>
              <div style={{ display: "flex", gap: "var(--space-2)", flexWrap: "wrap" }}>
                {availableThemes.map((t) => (
                  <button
                    key={t.id}
                    onClick={() => setBrand(t.id as ThemeBrand)}
                    className={`btn ${brand === t.id ? "btn-primary" : "btn-secondary"}`}
                    style={{ flex: "1 1 auto", minWidth: "120px" }}
                  >
                    {t.name}
                  </button>
                ))}
              </div>
              <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
                {availableThemes.find((t) => t.id === brand)?.description}
              </p>
            </div>

            <div className="form-group">
              <label className="label">Mode</label>
              <div style={{ display: "flex", gap: "var(--space-2)" }}>
                {(["dark", "auto", "light"] as ThemeMode[]).map((m) => (
                  <button
                    key={m}
                    onClick={() => setMode(m)}
                    className={`btn ${mode === m ? "btn-primary" : "btn-secondary"}`}
                    style={{ flex: 1 }}
                  >
                    {m === "dark" ? "\u25D0 Dark" : m === "light" ? "\u25CB Light" : "\u25D1 Auto"}
                  </button>
                ))}
              </div>
              <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
                Auto follows your system preference
              </p>
            </div>
          </div>
        </div>
      )}

      {/* System Actions */}
      {activeSection === "system" && (
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-4)" }}>
          {/* CPU Cores Configuration */}
          <div className="card">
            <h3 className="card-title">CPU Cores</h3>

            {cpuCores.pi_model && (
              <div style={{ marginBottom: "var(--space-4)" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--space-2)" }}>
                  <span className="text-secondary">Device</span>
                  <span className="text-primary">{cpuCores.pi_model.model_short}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span className="text-secondary">Recommended</span>
                  <span className="badge badge-info">{cpuCores.pi_model.default_active_cores} cores</span>
                </div>
              </div>
            )}

            <div className="form-group">
              <label className="label">Active Cores</label>
              <div style={{ display: "flex", alignItems: "center", gap: "var(--space-3)", marginBottom: "var(--space-3)" }}>
                <span style={{ fontSize: "1.5rem", fontWeight: 600, color: "var(--color-primary)", fontFamily: "var(--font-mono)" }}>
                  {cpuCores.online_cores}
                </span>
                <span className="text-muted">of {cpuCores.total_cores} cores active</span>
                {cpuCores.configured_cores && cpuCores.configured_cores !== cpuCores.online_cores && (
                  <span className="badge badge-warning">
                    {cpuCores.configured_cores} configured (reboot pending)
                  </span>
                )}
              </div>

              <div style={{ display: "flex", gap: "var(--space-2)", flexWrap: "wrap", marginBottom: "var(--space-3)" }}>
                {Array.from({ length: cpuCores.total_cores }, (_, i) => i + 1).map((num) => {
                  const isConfigured = effectiveCores === num;
                  const isSelected = selectedCores === num;
                  const showAsSelected = isSelected || (selectedCores === null && isConfigured);

                  return (
                    <button
                      key={num}
                      type="button"
                      onClick={() => setSelectedCores(num === effectiveCores ? null : num)}
                      className={`btn ${showAsSelected ? "btn-primary" : "btn-secondary"}`}
                      style={{
                        minWidth: "3rem",
                        fontFamily: "var(--font-mono)",
                      }}
                    >
                      {num}
                    </button>
                  );
                })}
              </div>

              {selectedCores !== null && selectedCores !== effectiveCores && (
                <Form method="post">
                  <input type="hidden" name="_action" value="set_cpu_cores" />
                  <input type="hidden" name="num_cores" value={selectedCores} />
                  <button
                    type="submit"
                    className="btn btn-warning"
                    disabled={isSubmitting}
                    onClick={(e) => {
                      if (!confirm(`Set CPU to ${selectedCores} cores and reboot the system?`)) {
                        e.preventDefault();
                      }
                    }}
                    style={{ width: "100%" }}
                  >
                    {isSubmitting ? (
                      <>
                        <span className="spinner"></span>
                        <span>Saving...</span>
                      </>
                    ) : (
                      <>
                        <span>🔄</span>
                        <span>Save and Reboot ({selectedCores} cores)</span>
                      </>
                    )}
                  </button>
                </Form>
              )}

              <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-3)" }}>
                Fewer active cores = lower power consumption and heat.
                {cpuCores.pi_model?.model_short?.includes("Zero 2") && (
                  <> Pi Zero 2 W works best with 2 cores for thermal management.</>
                )}
                {selectedCores !== null && selectedCores !== effectiveCores && (
                  <strong style={{ display: "block", marginTop: "var(--space-2)", color: "var(--color-warning)" }}>
                    System will reboot to apply this change.
                  </strong>
                )}
              </p>
            </div>
          </div>

          {/* System Actions */}
          <div className="card">
            <h3 className="card-title">System Actions</h3>

            <div className="form-group">
              <label className="label">Restart Backend</label>
            <Form method="post">
              <input type="hidden" name="_action" value="restart" />
              <button
                type="submit"
                className="btn btn-secondary"
                disabled={isSubmitting}
              >
                <span>🔄</span>
                <span>Restart Backend Service</span>
              </button>
            </Form>
            <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
              Restart the Dangerous Pi backend service (frontend will remain available)
            </p>
          </div>

          <div className="form-group">
            <label className="label">Shutdown System</label>
            <Form method="post">
              <input type="hidden" name="_action" value="shutdown" />
              <button
                type="submit"
                className="btn btn-danger"
                disabled={isSubmitting}
                onClick={(e) => {
                  if (!confirm("Are you sure you want to shutdown the system?")) {
                    e.preventDefault();
                  }
                }}
              >
                <span>⏻</span>
                <span>Shutdown Pi</span>
              </button>
            </Form>
            <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
              Safely shutdown the Raspberry Pi
            </p>
          </div>

          <div className="form-group">
            <label className="label">Backup & Restore</label>
            <div style={{ display: "flex", gap: "var(--space-2)", flexWrap: "wrap" }}>
              <button className="btn btn-secondary" disabled>
                <span>💾</span>
                <span>Create Backup</span>
              </button>
              <button className="btn btn-secondary" disabled>
                <span>📥</span>
                <span>Restore Backup</span>
              </button>
            </div>
            <p className="text-muted" style={{ fontSize: "0.75rem", marginTop: "var(--space-2)" }}>
              Backup and restore system configuration
            </p>
          </div>
        </div>
      </div>
      )}
    </div>
  );
}
