"use client";

import { useEffect, useState } from "react";

export default function ContextEditor() {
  const [activeTab, setActiveTab] = useState<"prompt" | "rules">("prompt");
  const [promptText, setPromptText] = useState("");
  const [rulesText, setRulesText] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [saveMessage, setSaveMessage] = useState("");

  // Load rules and prompt on mount
  useEffect(() => {
    const loadData = async () => {
      try {
        const res = await fetch("/api/context");
        if (res.ok) {
          const data = await res.json();
          setPromptText(data.prompt || "");
          setRulesText(data.rules || "");
        }
      } catch (err) {
        console.error("Failed to load context:", err);
      }
    };
    loadData();
  }, []);

  const handleSave = async () => {
    setIsSaving(true);
    setSaveMessage("");
    try {
      const res = await fetch("/api/context", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ promptText, rulesText }),
      });
      if (res.ok) {
        setSaveMessage("✓ Saved and staging recompiled successfully!");
        setTimeout(() => setSaveMessage(""), 4000);
      } else {
        setSaveMessage("✗ Error saving context files.");
      }
    } catch (err) {
      console.error(err);
      setSaveMessage("✗ Network failure.");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div 
      style={{
        border: "1px solid var(--border)",
        borderRadius: "12px",
        backgroundColor: "var(--card)",
        overflow: "hidden",
        marginTop: "1.5rem"
      }}
    >
      {/* Editor Headers */}
      <div 
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          background: "hsla(var(--border-hsl), 0.3)",
          borderBottom: "1px solid var(--border)",
          padding: "0.5rem 1rem"
        }}
      >
        <div style={{ display: "flex", gap: "0.5rem" }}>
          <button
            onClick={() => setActiveTab("prompt")}
            style={{
              padding: "0.5rem 1rem",
              borderRadius: "6px",
              border: "none",
              background: activeTab === "prompt" ? "var(--border)" : "transparent",
              color: activeTab === "prompt" ? "var(--foreground)" : "var(--muted)",
              fontSize: "0.825rem",
              fontWeight: 600,
            }}
          >
            ✏️ Staged Prompt (cprompt.md)
          </button>
          <button
            onClick={() => setActiveTab("rules")}
            style={{
              padding: "0.5rem 1rem",
              borderRadius: "6px",
              border: "none",
              background: activeTab === "rules" ? "var(--border)" : "transparent",
              color: activeTab === "rules" ? "var(--foreground)" : "var(--muted)",
              fontSize: "0.825rem",
              fontWeight: 600,
            }}
          >
            📋 System Rules (AGENTS.md)
          </button>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
          {saveMessage && <span style={{ fontSize: "0.75rem", color: saveMessage.startsWith("✓") ? "var(--success)" : "var(--danger)" }}>{saveMessage}</span>}
          <button
            onClick={handleSave}
            disabled={isSaving}
            style={{
              padding: "0.4rem 1rem",
              borderRadius: "6px",
              border: "none",
              backgroundColor: "var(--primary)",
              color: "#fff",
              fontSize: "0.75rem",
              fontWeight: 600,
              opacity: isSaving ? 0.7 : 1,
            }}
          >
            {isSaving ? "Saving..." : "Save & Recompile"}
          </button>
        </div>
      </div>

      {/* Editor Textarea */}
      <div style={{ position: "relative" }}>
        {activeTab === "prompt" ? (
          <textarea
            value={promptText}
            onChange={(e) => setPromptText(e.target.value)}
            placeholder="Type staged instructions for your next prompt trigger (/ccp)..."
            style={{
              width: "100%",
              height: "220px",
              padding: "1rem",
              background: "#080c14",
              border: "none",
              color: "#c9d1d9",
              fontFamily: "var(--font-mono), monospace",
              fontSize: "0.825rem",
              lineHeight: 1.5,
              resize: "vertical",
              outline: "none"
            }}
          />
        ) : (
          <textarea
            value={rulesText}
            onChange={(e) => setRulesText(e.target.value)}
            placeholder="Define global instructions, guidelines, style patterns for your agents..."
            style={{
              width: "100%",
              height: "220px",
              padding: "1rem",
              background: "#080c14",
              border: "none",
              color: "#c9d1d9",
              fontFamily: "var(--font-mono), monospace",
              fontSize: "0.825rem",
              lineHeight: 1.5,
              resize: "vertical",
              outline: "none"
            }}
          />
        )}
      </div>
    </div>
  );
}
