"use client";

import { useEffect, useState } from "react";
import DirectoryBrowserModal from "./DirectoryBrowserModal";

interface AiderConfig {
  openaiApiKey: string;
  anthropicApiKey: string;
  geminiApiKey: string;
  model: string;
  extraFlags: string;
  workspaceRoot: string;
  scopedDirs: string[];
}

interface AiderWizardProps {
  onClose: () => void;
  onConfirmLaunch: () => void;
  isDocker: boolean;
}

export default function AiderWizard({ onClose, onConfirmLaunch, isDocker }: AiderWizardProps) {
  const [config, setConfig] = useState<AiderConfig>({
    openaiApiKey: "",
    anthropicApiKey: "",
    geminiApiKey: "",
    model: "claude-3-5-sonnet",
    extraFlags: "",
    workspaceRoot: "",
    scopedDirs: [],
  });

  const [newScopePath, setNewScopePath] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [isBrowsingWorkspace, setIsBrowsingWorkspace] = useState(false);
  const [isBrowsingScope, setIsBrowsingScope] = useState(false);

  // Load config on mount
  useEffect(() => {
    const loadConfig = async () => {
      try {
        const res = await fetch("/api/context/aider");
        if (res.ok) {
          const data = await res.json();
          if (data.success && data.config) {
            setConfig({
              openaiApiKey: data.config.openaiApiKey || "",
              anthropicApiKey: data.config.anthropicApiKey || "",
              geminiApiKey: data.config.geminiApiKey || "",
              model: data.config.model || "claude-3-5-sonnet",
              extraFlags: data.config.extraFlags || "",
              workspaceRoot: data.config.workspaceRoot || "",
              scopedDirs: data.config.scopedDirs || [],
            });
          }
        }
      } catch (err) {
        console.error("Failed to load Aider configuration:", err);
      } finally {
        setIsLoading(false);
      }
    };

    loadConfig();
  }, []);

  const handleSaveAndLaunch = async () => {
    setIsSaving(true);
    setErrorMessage("");

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

      if (res.ok) {
        setIsSaving(false);
        onConfirmLaunch();
      } else {
        const data = await res.json();
        setErrorMessage(data.error || "Failed to save settings.");
        setIsSaving(false);
      }
    } catch (err) {
      console.error(err);
      setErrorMessage("Network error: failed to connect to NeuralLoom dashboard API.");
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <div style={modalOverlayStyle}>
        <div style={modalContainerStyle}>
          <div style={{ textAlign: "center", padding: "2rem" }}>
            <span style={{ color: "var(--muted)" }}>Loading Aider 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" }}>
            🐍 Aider Launch Panel {isDocker ? "(Docker)" : ""}
          </h3>
          <button onClick={onClose} style={closeButtonStyle} aria-label="Close wizard">✖</button>
        </div>

        {/* Body */}
        <div style={bodyStyle}>
          <p style={{ fontSize: "0.825rem", color: "var(--muted)", marginBottom: "1.25rem", lineHeight: 1.4 }}>
            Configure model and environment variables for the Aider session. API keys are saved locally in `.ai/neural-loom/aider.json` and are ignored by git.
          </p>

          <div style={formGroupStyle}>
            <label style={labelStyle}>Anthropic API Key</label>
            <input
              type="password"
              value={config.anthropicApiKey}
              onChange={(e) => setConfig({ ...config, anthropicApiKey: e.target.value })}
              placeholder={config.anthropicApiKey ? "••••••••••••••••" : "sk-ant-..."}
              style={inputStyle}
            />
          </div>

          <div style={formGroupStyle}>
            <label style={labelStyle}>OpenAI API Key</label>
            <input
              type="password"
              value={config.openaiApiKey}
              onChange={(e) => setConfig({ ...config, openaiApiKey: e.target.value })}
              placeholder={config.openaiApiKey ? "••••••••••••••••" : "sk-..."}
              style={inputStyle}
            />
          </div>

          <div style={formGroupStyle}>
            <label style={labelStyle}>Gemini API Key</label>
            <input
              type="password"
              value={config.geminiApiKey}
              onChange={(e) => setConfig({ ...config, geminiApiKey: e.target.value })}
              placeholder={config.geminiApiKey ? "••••••••••••••••" : "AIzaSy..."}
              style={inputStyle}
            />
          </div>

          <div style={formGroupStyle}>
            <label style={labelStyle}>Workspace Directory (Root)</label>
            <div style={{ display: "flex", gap: "0.5rem" }}>
              <input
                type="text"
                value={config.workspaceRoot}
                onChange={(e) => setConfig({ ...config, workspaceRoot: e.target.value })}
                placeholder="e.g. C:\Users\Dave\OneDrive\Projects\JS\neural-loom"
                style={{ ...inputStyle, flex: 1 }}
              />
              <button
                type="button"
                onClick={() => setIsBrowsingWorkspace(true)}
                style={browseButtonStyle}
              >
                Browse...
              </button>
            </div>
            <span style={{ fontSize: "0.7rem", color: "var(--muted)", marginTop: "0.25rem" }}>
              Leave blank to default to the current orchestrator directory.
            </span>
          </div>

          <div style={formGroupStyle}>
            <label style={labelStyle}>Scoped Directories (Additional Access)</label>
            {config.scopedDirs.length > 0 && (
              <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem", marginBottom: "0.5rem" }}>
                {config.scopedDirs.map((dir, index) => (
                  <div key={index} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", backgroundColor: "#080c14", padding: "0.35rem 0.5rem", borderRadius: "4px", border: "1px solid var(--border)" }}>
                    <span style={{ fontSize: "0.8rem", fontFamily: "var(--font-mono), monospace", wordBreak: "break-all" }}>{dir}</span>
                    <button
                      type="button"
                      onClick={() => {
                        const updated = config.scopedDirs.filter((_, i) => i !== index);
                        setConfig({ ...config, scopedDirs: updated });
                      }}
                      style={{ background: "none", border: "none", color: "var(--danger)", cursor: "pointer", fontSize: "0.8rem", padding: "0 0.25rem" }}
                    >
                      Remove
                    </button>
                  </div>
                ))}
              </div>
            )}
            <div style={{ display: "flex", gap: "0.5rem" }}>
              <input
                type="text"
                value={newScopePath}
                onChange={(e) => setNewScopePath(e.target.value)}
                placeholder="e.g. C:\Users\Dave\OneDrive\Projects\JS\wingman"
                style={{ ...inputStyle, flex: 1 }}
              />
              <button
                type="button"
                onClick={() => setIsBrowsingScope(true)}
                style={browseButtonStyle}
              >
                Browse...
              </button>
              <button
                type="button"
                onClick={() => {
                  if (newScopePath.trim() && !config.scopedDirs.includes(newScopePath.trim())) {
                    setConfig({
                      ...config,
                      scopedDirs: [...config.scopedDirs, newScopePath.trim()]
                    });
                    setNewScopePath("");
                  }
                }}
                style={{
                  padding: "0.35rem 0.75rem",
                  borderRadius: "6px",
                  border: "1px solid var(--border-focus)",
                  backgroundColor: "rgba(109, 40, 217, 0.1)",
                  color: "var(--foreground)",
                  fontSize: "0.75rem",
                  fontWeight: 600,
                  cursor: "pointer"
                }}
              >
                Add
              </button>
            </div>
          </div>

          <div style={formGroupStyle}>
            <label style={labelStyle}>AI Model Selection</label>
            <select
              value={config.model}
              onChange={(e) => setConfig({ ...config, model: e.target.value })}
              style={selectStyle}
            >
              <option value="claude-3-5-sonnet">Claude 3.5 Sonnet (Recommended)</option>
              <option value="gemini/gemini-1.5-pro">Gemini 1.5 Pro</option>
              <option value="gemini/gemini-1.5-flash">Gemini 1.5 Flash</option>
              <option value="gemini/gemini-2.0-flash-exp">Gemini 2.0 Flash Exp</option>
              <option value="gpt-4o">GPT-4o</option>
              <option value="deepseek/deepseek-coder">DeepSeek Coder</option>
              <option value="gpt-4-turbo">GPT-4 Turbo</option>
            </select>
          </div>

          <div style={formGroupStyle}>
            <label style={labelStyle}>Extra CLI Flags (Optional)</label>
            <input
              type="text"
              value={config.extraFlags}
              onChange={(e) => setConfig({ ...config, extraFlags: e.target.value })}
              placeholder="e.g. --no-git --auto-commits"
              style={inputStyle}
            />
            <span style={{ fontSize: "0.7rem", color: "var(--muted)", marginTop: "0.25rem" }}>
              Appended directly to the startup shell command.
            </span>
          </div>

          {errorMessage && (
            <div style={errorBoxStyle}>
              ✗ {errorMessage}
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={footerStyle}>
          <button onClick={onClose} style={secondaryButtonStyle} disabled={isSaving}>
            Cancel
          </button>
          <button
            onClick={handleSaveAndLaunch}
            style={primaryButtonStyle}
            disabled={isSaving}
          >
            {isSaving ? "Saving..." : "Save & Launch Session"}
          </button>
        </div>
        {isBrowsingWorkspace && (
          <DirectoryBrowserModal
            title="Select Workspace Root"
            initialPath={config.workspaceRoot}
            onClose={() => setIsBrowsingWorkspace(false)}
            onSelect={(selectedPath) => setConfig({ ...config, workspaceRoot: selectedPath })}
          />
        )}

        {isBrowsingScope && (
          <DirectoryBrowserModal
            title="Add Scoped Directory"
            initialPath={newScopePath}
            onClose={() => setIsBrowsingScope(false)}
            onSelect={(selectedPath) => setNewScopePath(selectedPath)}
          />
        )}
      </div>
    </div>
  );
}

// Reuse modal styles for theme cohesion
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 selectStyle: React.CSSProperties = {
  width: "100%",
  padding: "0.5rem 0.75rem",
  backgroundColor: "#080c14",
  border: "1px solid var(--border)",
  borderRadius: "6px",
  color: "var(--foreground)",
  fontSize: "0.825rem",
  outline: "none",
  cursor: "pointer",
};

const errorBoxStyle: React.CSSProperties = {
  marginTop: "0.75rem",
  padding: "0.75rem",
  borderRadius: "6px",
  border: "1px solid var(--danger)",
  backgroundColor: "rgba(239, 68, 68, 0.05)",
  color: "var(--danger)",
  fontSize: "0.8rem",
  lineHeight: 1.4,
};

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(210, 80%, 45%) 0%, hsl(262, 80%, 55%) 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",
};

const browseButtonStyle: React.CSSProperties = {
  padding: "0.35rem 0.75rem",
  borderRadius: "6px",
  border: "1px solid var(--border)",
  backgroundColor: "rgba(255, 255, 255, 0.05)",
  color: "var(--foreground)",
  fontSize: "0.75rem",
  fontWeight: 600,
  cursor: "pointer",
  transition: "all 0.15s ease",
};
