import { postJson } from "../api/controlApi";

export function StackPresetToolbar({
  presetName,
  selectedPresetName,
  stackPresets,
  onPresetNameChange,
  onSelectedPresetNameChange,
}) {
  return (
    <div className="panel stack-panel">
      <div className="panel__header stack-panel__header">
        <div>
          <h3>Stack presets</h3>
          <p className="muted">Save or recall the current layer chain.</p>
        </div>
        <button type="button" className="stack-panel__reload" onClick={() => postJson("/api/reload", {})}>
          Reload shader
        </button>
      </div>

      <div className="stack-panel__grid">
        <div className="toolbar__group">
          <label htmlFor="preset-name">Save stack</label>
          <div className="toolbar__inline">
            <input
              id="preset-name"
              type="text"
              placeholder="Preset name"
              value={presetName}
              onChange={(event) => onPresetNameChange(event.target.value)}
            />
            <button
              type="button"
              disabled={!presetName.trim()}
              onClick={() => {
                const trimmedName = presetName.trim();
                if (!trimmedName) {
                  return;
                }
                postJson("/api/stack-presets/save", { presetName: trimmedName });
                onSelectedPresetNameChange(
                  trimmedName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""),
                );
              }}
            >
              Save
            </button>
          </div>
        </div>

        <div className="toolbar__group">
          <label htmlFor="preset-select">Recall stack</label>
          <div className="toolbar__inline">
            <select
              id="preset-select"
              value={selectedPresetName}
              onChange={(event) => onSelectedPresetNameChange(event.target.value)}
            >
              {stackPresets.length === 0 ? <option value="">No presets</option> : null}
              {stackPresets.map((preset) => (
                <option key={preset} value={preset}>
                  {preset}
                </option>
              ))}
            </select>
            <button
              type="button"
              disabled={!selectedPresetName}
              onClick={() => {
                if (selectedPresetName) {
                  postJson("/api/stack-presets/load", { presetName: selectedPresetName });
                }
              }}
            >
              Recall
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
