import React, { useState, useEffect } from "react";

const api = window.api;

export function GitSettings() {
  // null = setting not yet loaded; true/false = loaded value
  const [branchingEnabled, setBranchingEnabled] = useState<boolean | null>(null);
  const [saveStatus, setSaveStatus] = useState<"idle" | "saved">("idle");

  useEffect(() => {
    api.getSettings(["git.branchingEnabled"]).then((settings) => {
      // Key absent or any value other than "true" → false (opt-in default)
      setBranchingEnabled(settings["git.branchingEnabled"] === "true");
    });
  }, []);

  const handleToggle = async (enabled: boolean) => {
    setBranchingEnabled(enabled);
    if (enabled) {
      await api.setSetting("git.branchingEnabled", "true");
    } else {
      await api.deleteSetting("git.branchingEnabled");
    }
    setSaveStatus("saved");
    setTimeout(() => setSaveStatus("idle"), 1500);
  };

  if (branchingEnabled === null) {
    return (
      <div style={{ color: "var(--text-secondary)", fontSize: 12 }}>
        Loading...
      </div>
    );
  }

  return (
    <div>
      <div className="settings-section-title">Git</div>
      <div className="settings-section-desc">
        Configure how Claude Flow interacts with your project's git repository
        during the implement phase.
      </div>

      <div className="settings-toggle-row">
        <label className="settings-toggle-label" htmlFor="git-branching-toggle">
          <span className="settings-toggle-text">
            <strong>Create a branch per session</strong>
            <span className="settings-toggle-hint">
              When enabled, Claude Flow checks out a new{" "}
              <code>claude-flow/&lt;name&gt;-&lt;id&gt;</code> branch when
              entering the implement phase. When disabled, commits land on
              your current branch.
            </span>
          </span>
          <span
            className={`settings-toggle${branchingEnabled ? " on" : ""}`}
            role="switch"
            aria-checked={branchingEnabled}
            id="git-branching-toggle"
            tabIndex={0}
            onClick={() => handleToggle(!branchingEnabled)}
            onKeyDown={(e) => {
              if (e.key === " " || e.key === "Enter") {
                e.preventDefault();
                handleToggle(!branchingEnabled);
              }
            }}
          />
        </label>
        {saveStatus === "saved" && (
          <span className="settings-custom-badge" style={{ color: "var(--accent)" }}>
            saved ✓
          </span>
        )}
      </div>
    </div>
  );
}
