"use client";

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

interface ClaudeConfig {
  name: string;
  workspaceRoot: string;
  scopedDirs: string[];
}

interface ClaudeWizardProps {
  onClose: () => void;
  onConfirmLaunch: (name: string, workspaceRoot: string, scopedDirs: string[]) => void;
  isDocker: boolean;
}

export default function ClaudeWizard({ onClose, onConfirmLaunch, isDocker }: ClaudeWizardProps) {
  const [config, setConfig] = useState<ClaudeConfig>({
    name: isDocker ? "Claude Docker" : "Claude Local",
    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/claude");
        if (res.ok) {
          const data = await res.json();
          if (data.success && data.config) {
            setConfig({
              name: data.config.name || (isDocker ? "Claude Docker" : "Claude Local"),
              workspaceRoot: data.config.workspaceRoot || "",
              scopedDirs: data.config.scopedDirs || [],
            });
          }
        }
      } catch (err) {
        console.error("Failed to load Claude configuration:", err);
      } finally {
        setIsLoading(false);
      }
    };

    loadConfig();
  }, [isDocker]);

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

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

      if (res.ok) {
        setIsSaving(false);
        onConfirmLaunch(config.name, config.workspaceRoot, config.scopedDirs);
      } 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 Claude 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" }}>
            {isDocker ? "🐳" : "🤖"} Claude PTY Launch Wizard {isDocker ? "(Docker)" : "(Local)"}
          </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 the local workspace path and access parameters for the Claude Code session. Settings are saved in `.ai/neural-loom/claude.json`.
          </p>

          <div style={formGroupStyle}>
            <label style={labelStyle}>Session Display Name</label>
            <input
              type="text"
              value={config.name}
              onChange={(e) => setConfig({ ...config, name: e.target.value })}
              placeholder={isDocker ? "Claude Docker" : "Claude Local"}
              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\wingman"
                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" }}>
              The active folder Claude Code will run in. Leave blank to run in 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\other-repo"
                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>

          {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..." : "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>
  );
}

// Modal styling cohesive with dashboard
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 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(262, 83%, 60%) 0%, hsl(195, 100%, 45%) 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",
};
