import { useState } from "react";
import { getSetting, setSetting, SettingKey } from "../settings";

type Props = {
  onClose: () => void;
};

export default function Settings({ onClose }: Props) {
  const [address, setAddress] = useState(getSetting(SettingKey.Address));
  const [token, setToken] = useState(getSetting(SettingKey.Token));
  const [saved, setSaved] = useState(false);

  function handleSave() {
    setSetting(SettingKey.Address, address);
    setSetting(SettingKey.Token, token);
    setSaved(true);
  }

  return (
    <div className="modalBackdrop" onClick={onClose}>
      <div className="modalCard" onClick={e => e.stopPropagation()}>
        <h3>Settings</h3>

        <label>
          API Address
          <input type="text" value={address} onChange={e => { setAddress(e.target.value); setSaved(false); }} />
        </label>

        <label>
          Auth Token
          <input type="text" value={token} onChange={e => { setToken(e.target.value); setSaved(false); }} />
        </label>

        <p className="warningText">Stored locally in this browser only.</p>

        {saved && <p>Saved.</p>}

        <div className="flexboxHorizontal">
          <button onClick={handleSave}>Save</button>
          <button className="normalButton" onClick={onClose}>Close</button>
        </div>
      </div>
    </div>
  );
}