import { useState, useEffect } from "react";
import type { Instance } from "../types";
import { fetchInstanceConfig, sendSetInstanceConfigRequest } from "../api";

type Props = {
  instance: Instance;
};

export default function InstanceConfig({ instance }: Props) {
  const [config, setConfig] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchInstanceConfig(instance.name)
      .then(setConfig)
      .catch(e => setError(e.message ?? String(e)))
      .finally(() => setLoading(false));
  }, [instance.name]);

  async function handleSave() {
    setSaving(true);
    setError(null);
    try {
      await sendSetInstanceConfigRequest(instance.name, config);
    } catch (e: any) {
      setError(e.message ?? String(e));
    } finally {
      setSaving(false);
    }
  }

  if (loading) return <p>Loading config...</p>;

  return (
    <div className="configEditor">
      {error && <div className="error">Error: {error}</div>}
      <textarea
        value={config}
        onChange={e => setConfig(e.target.value)}
        rows={25}
        spellCheck={false}
      />
      <button disabled={saving} onClick={handleSave}>
        {saving ? "Saving..." : "Save"}
      </button>
    </div>
  );
}