import React, { useState, useEffect } from "react";
import type { Phase } from "../../types";

const api = window.api;

const PHASES: Phase[] = ["research", "plan", "implement"];
const PHASE_LABELS: Record<Phase, string> = {
  research: "Research",
  plan: "Plan",
  implement: "Implement",
};

export function ModelSettings() {
  // ── Global default ───────────────────────────────────────────
  const [model, setModel] = useState<string | null>(null);
  const [draft, setDraft] = useState("");
  const [saveStatus, setSaveStatus] = useState<"idle" | "saved">("idle");

  // ── Per-phase overrides ──────────────────────────────────────
  const [phaseModels, setPhaseModels] = useState<Record<Phase, string | null>>({
    research: null,
    plan: null,
    implement: null,
  });
  const [phaseDrafts, setPhaseDrafts] = useState<Record<Phase, string>>({
    research: "",
    plan: "",
    implement: "",
  });
  const [phaseStatus, setPhaseStatus] = useState<Record<Phase, "idle" | "saved">>({
    research: "idle",
    plan: "idle",
    implement: "idle",
  });

  useEffect(() => {
    api
      .getSettings(["model", "model.research", "model.plan", "model.implement"])
      .then((settings) => {
        const saved = settings["model"] ?? "";
        setModel(saved);
        setDraft(saved);

        const pm: Record<Phase, string | null> = {
          research: settings["model.research"],
          plan: settings["model.plan"],
          implement: settings["model.implement"],
        };
        setPhaseModels(pm);
        setPhaseDrafts({
          research: pm.research ?? "",
          plan: pm.plan ?? "",
          implement: pm.implement ?? "",
        });
      });
  }, []);

  // ── Global handlers ──────────────────────────────────────────
  const handleSave = async () => {
    const trimmed = draft.trim();
    if (trimmed) {
      await api.setSetting("model", trimmed);
      setModel(trimmed);
    } else {
      await api.deleteSetting("model");
      setModel("");
    }
    setSaveStatus("saved");
    setTimeout(() => setSaveStatus("idle"), 1500);
  };

  const handleReset = async () => {
    await api.deleteSetting("model");
    setModel("");
    setDraft("");
    setSaveStatus("saved");
    setTimeout(() => setSaveStatus("idle"), 1500);
  };

  // ── Per-phase handlers ───────────────────────────────────────
  const handlePhaseSave = async (phase: Phase) => {
    const trimmed = phaseDrafts[phase].trim();
    if (trimmed) {
      await api.setSetting(`model.${phase}`, trimmed);
      setPhaseModels((prev) => ({ ...prev, [phase]: trimmed }));
    } else {
      await api.deleteSetting(`model.${phase}`);
      setPhaseModels((prev) => ({ ...prev, [phase]: null }));
    }
    setPhaseStatus((prev) => ({ ...prev, [phase]: "saved" }));
    setTimeout(
      () => setPhaseStatus((prev) => ({ ...prev, [phase]: "idle" })),
      1500
    );
  };

  const handlePhaseReset = async (phase: Phase) => {
    await api.deleteSetting(`model.${phase}`);
    setPhaseModels((prev) => ({ ...prev, [phase]: null }));
    setPhaseDrafts((prev) => ({ ...prev, [phase]: "" }));
    setPhaseStatus((prev) => ({ ...prev, [phase]: "saved" }));
    setTimeout(
      () => setPhaseStatus((prev) => ({ ...prev, [phase]: "idle" })),
      1500
    );
  };

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

  const isDirty = draft.trim() !== model;

  return (
    <div>
      {/* ── Global default ──────────────────────────────────── */}
      <div className="settings-section-title">Default Model</div>
      <div className="settings-section-desc">
        Fallback model used for all phases unless a per-phase override is set.
        Leave blank to use the SDK&apos;s built-in default.
      </div>

      <div className="settings-toggle-row">
        <input
          className="settings-model-input"
          type="text"
          value={draft}
          placeholder="e.g. claude-sonnet-4-5"
          onChange={(e) => {
            setDraft(e.target.value);
            setSaveStatus("idle");
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter") handleSave();
          }}
          spellCheck={false}
        />
      </div>

      <div className="settings-actions">
        {model && (
          <button className="btn-secondary" onClick={handleReset}>
            Reset
          </button>
        )}
        <button
          className="btn-primary"
          onClick={handleSave}
          disabled={!isDirty}
        >
          {saveStatus === "saved" ? "Saved \u2713" : "Save"}
        </button>
        {model && <span className="settings-custom-badge">custom</span>}
      </div>

      {/* ── Per-phase overrides ─────────────────────────────── */}
      <div className="settings-section-title" style={{ marginTop: 24 }}>
        Phase Overrides
      </div>
      <div className="settings-section-desc">
        Use a different model for a specific phase. Leave blank to inherit the
        default above. Takes effect on the next message in any session.
      </div>

      <div className="settings-phase-model-list">
        {PHASES.map((phase) => {
          const saved = phaseModels[phase];
          const phaseDirty = phaseDrafts[phase].trim() !== (saved ?? "");

          return (
            <div key={phase} className="settings-phase-model-row">
              <span className="settings-phase-model-label">
                {PHASE_LABELS[phase]}
              </span>
              <input
                className="settings-model-input"
                type="text"
                value={phaseDrafts[phase]}
                placeholder={model ? `Inherits: ${model}` : "Inherits default"}
                onChange={(e) => {
                  setPhaseDrafts((prev) => ({
                    ...prev,
                    [phase]: e.target.value,
                  }));
                  setPhaseStatus((prev) => ({ ...prev, [phase]: "idle" }));
                }}
                onKeyDown={(e) => {
                  if (e.key === "Enter") handlePhaseSave(phase);
                }}
                spellCheck={false}
              />
              <div className="settings-phase-model-actions">
                {saved && (
                  <button
                    className="btn-secondary"
                    onClick={() => handlePhaseReset(phase)}
                  >
                    Reset
                  </button>
                )}
                <button
                  className="btn-primary"
                  onClick={() => handlePhaseSave(phase)}
                  disabled={!phaseDirty}
                >
                  {phaseStatus[phase] === "saved" ? "Saved \u2713" : "Save"}
                </button>
                {saved && (
                  <span className="settings-custom-badge">custom</span>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
