"use client";

import { useEffect, useState } from "react";

interface SshConfig {
  host: string;
  port: number;
  username: string;
  privateKeyPath: string;
}

interface SshWizardProps {
  onClose: () => void;
  onConfirmLaunch: () => void;
}

export default function SshWizard({ onClose, onConfirmLaunch }: SshWizardProps) {
  const [config, setConfig] = useState<SshConfig>({
    host: "",
    port: 22,
    username: "",
    privateKeyPath: "",
  });

  const [isLoading, setIsLoading] = useState(true);
  const [isTesting, setIsTesting] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);

  // Load saved credentials on mount
  useEffect(() => {
    const loadConfig = async () => {
      try {
        const res = await fetch("/api/context/ssh");
        if (res.ok) {
          const data = await res.json();
          if (data.success && data.config) {
            setConfig({
              host: data.config.host || "",
              port: data.config.port || 22,
              username: data.config.username || "",
              privateKeyPath: data.config.privateKeyPath || "",
            });
          }
        }
      } catch (err) {
        console.error("Failed to load SSH configuration:", err);
      } finally {
        setIsLoading(false);
      }
    };

    loadConfig();
  }, []);

  const handleTestConnection = async () => {
    if (!config.host || !config.username) {
      setTestResult({ success: false, message: "Host and Username are required to test connection." });
      return;
    }

    setIsTesting(true);
    setTestResult(null);

    try {
      const res = await fetch("/api/context/ssh", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          test: true,
          ...config,
        }),
      });

      if (res.ok) {
        const data = await res.json();
        setTestResult({
          success: data.success,
          message: data.message || (data.success ? "Connection successful!" : "Connection failed."),
        });
      } else {
        const data = await res.json();
        setTestResult({
          success: false,
          message: data.error || "Failed to reach testing endpoint.",
        });
      }
    } catch (err) {
      console.error(err);
      setTestResult({
        success: false,
        message: "Network error occurred while testing connection.",
      });
    } finally {
      setIsTesting(false);
    }
  };

  const handleSaveAndLaunch = async () => {
    if (!config.host || !config.username) {
      setTestResult({ success: false, message: "Host and Username are required to save." });
      return;
    }

    setIsSaving(true);
    setTestResult(null);

    try {
      const res = await fetch("/api/context/ssh", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          test: false,
          ...config,
        }),
      });

      if (res.ok) {
        setIsSaving(false);
        onConfirmLaunch();
      } else {
        const data = await res.json();
        setTestResult({
          success: false,
          message: data.error || "Failed to save settings.",
        });
        setIsSaving(false);
      }
    } catch (err) {
      console.error(err);
      setTestResult({
        success: false,
        message: "Failed to connect to NeuralLoom save endpoint.",
      });
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <div style={modalOverlayStyle}>
        <div style={modalContainerStyle}>
          <div style={{ textAlign: "center", padding: "2rem" }}>
            <span style={{ color: "var(--muted)" }}>Loading SSH Configuration...</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={modalOverlayStyle}>
      <div style={modalContainerStyle}>
        {/* Header */}
        <div style={headerStyle}>
          <h3 style={{ fontSize: "1.1rem", fontWeight: 700, margin: 0, display: "flex", alignItems: "center", gap: "0.5rem" }}>
            🌐 SSH Connection Wizard
          </h3>
          <button onClick={onClose} style={closeButtonStyle} aria-label="Close wizard">✖</button>
        </div>

        {/* Form Body */}
        <div style={bodyStyle}>
          <p style={{ fontSize: "0.825rem", color: "var(--muted)", marginBottom: "1.25rem", lineHeight: 1.4 }}>
            Configure the remote VM connection. When you click <strong>Save & Launch</strong>, NeuralLoom will write to <code>ssh.json</code> and spawn Claude Code on the target host.
          </p>

          <div style={formGroupStyle}>
            <label style={labelStyle}>Host IP or Domain Name</label>
            <input
              type="text"
              value={config.host}
              onChange={(e) => setConfig({ ...config, host: e.target.value })}
              placeholder="e.g. 192.168.1.50 or host.remote.com"
              style={inputStyle}
            />
          </div>

          <div style={{ display: "flex", gap: "1rem" }}>
            <div style={{ ...formGroupStyle, flex: 2 }}>
              <label style={labelStyle}>Username</label>
              <input
                type="text"
                value={config.username}
                onChange={(e) => setConfig({ ...config, username: e.target.value })}
                placeholder="e.g. ubuntu, root, or dave"
                style={inputStyle}
              />
            </div>
            <div style={{ ...formGroupStyle, flex: 1 }}>
              <label style={labelStyle}>Port</label>
              <input
                type="number"
                value={config.port}
                onChange={(e) => setConfig({ ...config, port: parseInt(e.target.value, 10) || 22 })}
                placeholder="22"
                style={inputStyle}
              />
            </div>
          </div>

          <div style={formGroupStyle}>
            <label style={labelStyle}>Private Key File Path (Optional)</label>
            <input
              type="text"
              value={config.privateKeyPath}
              onChange={(e) => setConfig({ ...config, privateKeyPath: e.target.value })}
              placeholder="e.g. C:\Users\Dave\.ssh\id_rsa"
              style={inputStyle}
            />
            <span style={{ fontSize: "0.7rem", color: "var(--muted)", marginTop: "0.25rem" }}>
              Leave blank if using the default system SSH key agent.
            </span>
          </div>

          {/* Test connection progress / alert */}
          {isTesting && (
            <div style={{ ...alertBoxStyle, borderColor: "var(--border)", color: "var(--muted)" }}>
              <span className="pulseDot" style={{ marginRight: "0.5rem", display: "inline-block" }}></span>
              Connecting and testing SSH tunnel... (ConnectTimeout=3s)
            </div>
          )}

          {testResult && (
            <div
              style={{
                ...alertBoxStyle,
                borderColor: testResult.success ? "var(--success)" : "var(--danger)",
                color: testResult.success ? "var(--success)" : "var(--danger)",
                backgroundColor: testResult.success ? "rgba(16, 185, 129, 0.05)" : "rgba(239, 68, 68, 0.05)",
              }}
            >
              {testResult.success ? "✓ " : "✗ "}
              {testResult.message}
            </div>
          )}
        </div>

        {/* Footer Actions */}
        <div style={footerStyle}>
          <button onClick={onClose} style={secondaryButtonStyle} disabled={isSaving || isTesting}>
            Cancel
          </button>
          <button onClick={handleTestConnection} style={secondaryButtonStyle} disabled={isSaving || isTesting}>
            {isTesting ? "Testing..." : "Test Connection"}
          </button>
          <button
            onClick={handleSaveAndLaunch}
            style={primaryButtonStyle}
            disabled={isSaving || isTesting || !config.host || !config.username}
          >
            {isSaving ? "Saving..." : "Save & Launch Session"}
          </button>
        </div>
      </div>
    </div>
  );
}

// Styling definitions to keep dependencies clear and avoid style bleed
const modalOverlayStyle: React.CSSProperties = {
  position: "fixed",
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  backgroundColor: "rgba(5, 7, 10, 0.8)",
  backdropFilter: "blur(8px)",
  zIndex: 1000,
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  animation: "fadeIn 0.2s ease-out",
};

const modalContainerStyle: React.CSSProperties = {
  width: "90%",
  maxWidth: "500px",
  backgroundColor: "var(--card)",
  border: "1px solid var(--border-focus)",
  borderRadius: "12px",
  boxShadow: "0 10px 25px -5px rgba(0, 0, 0, 0.5), 0 8px 10px -6px rgba(0, 0, 0, 0.5)",
  overflow: "hidden",
  display: "flex",
  flexDirection: "column",
};

const headerStyle: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  padding: "1rem 1.25rem",
  borderBottom: "1px solid var(--border)",
  background: "hsla(var(--border-hsl), 0.2)",
};

const closeButtonStyle: React.CSSProperties = {
  background: "none",
  border: "none",
  color: "var(--muted)",
  fontSize: "0.9rem",
  cursor: "pointer",
  padding: "0.25rem",
};

const bodyStyle: React.CSSProperties = {
  padding: "1.25rem",
  display: "flex",
  flexDirection: "column",
};

const formGroupStyle: React.CSSProperties = {
  display: "flex",
  flexDirection: "column",
  marginBottom: "1rem",
};

const labelStyle: React.CSSProperties = {
  fontSize: "0.75rem",
  fontWeight: 600,
  color: "var(--foreground)",
  marginBottom: "0.375rem",
  textTransform: "uppercase",
  letterSpacing: "0.05em",
};

const inputStyle: React.CSSProperties = {
  width: "100%",
  padding: "0.5rem 0.75rem",
  backgroundColor: "#080c14",
  border: "1px solid var(--border)",
  borderRadius: "6px",
  color: "var(--foreground)",
  fontFamily: "var(--font-mono), monospace",
  fontSize: "0.825rem",
  outline: "none",
  transition: "border-color 0.15s ease",
};

const alertBoxStyle: React.CSSProperties = {
  marginTop: "0.75rem",
  padding: "0.75rem",
  borderRadius: "6px",
  border: "1px solid",
  fontSize: "0.8rem",
  lineHeight: 1.4,
  wordBreak: "break-word",
};

const footerStyle: React.CSSProperties = {
  display: "flex",
  justifyContent: "flex-end",
  gap: "0.75rem",
  padding: "1rem 1.25rem",
  borderTop: "1px solid var(--border)",
  background: "hsla(var(--border-hsl), 0.2)",
};

const primaryButtonStyle: React.CSSProperties = {
  padding: "0.5rem 1rem",
  borderRadius: "6px",
  border: "none",
  background: "linear-gradient(135deg, hsl(38, 92%, 50%) 0%, hsl(0, 84%, 60%) 100%)",
  color: "#fff",
  fontSize: "0.8rem",
  fontWeight: 600,
  cursor: "pointer",
};

const secondaryButtonStyle: React.CSSProperties = {
  padding: "0.5rem 1rem",
  borderRadius: "6px",
  border: "1px solid var(--border)",
  backgroundColor: "transparent",
  color: "var(--foreground)",
  fontSize: "0.8rem",
  fontWeight: 600,
  cursor: "pointer",
};
