import useLocalState from "@/state/state";
import type { UserProfile } from "@/types/nostril";
import { useState } from "react";

function Settings() {
  const { UISettings, keys, profiles, relays, api } = useLocalState();
  const [newRelay, setNewRelay] = useState("");
  async function saveSetting(
    bucket: string,
    key: string,
    value: string | boolean | number | string[],
  ) {
    const json = {
      "put-entry": {
        desk: "trill",
        "bucket-key": bucket,
        "entry-key": key,
        value,
      },
    };
    // const res = await poke("settings", "settings-event", json);
    // if (res) refetchSettings();
  }
  async function removeRelay(url: string) {
    console.log({ url });
  }
  async function addNewRelay() {
    //
    // await addnr(newRelay);
  }
  async function removeProfile(pubkey: string) {
    api!.removeKey(pubkey);
  }
  async function createProfile() {
    //
    api!.createKey();
  }

  return (
    <div id="settings">
      <h1>Settings</h1>
      <div className="setting">
        <label>Pubkeys</label>
        {keys.map((k) => {
          const profile = profiles.get(k);
          const profileDiv = !profile ? (
            <div className="profile">
              <div>Pubkey: {k}</div>
              <p>No profile set</p>)
            </div>
          ) : (
            <div className="profile">
              {profile.picture && <img src={profile.picture} />}
              <div>Name: {profile.name}</div>
              <div>Pubkey: {k}</div>
              <div>About: {profile.about}</div>
              <button onClick={() => removeProfile(k)}>x</button>
            </div>
          );
          return (
            <div className="options flex" key={k}>
              {profileDiv}
            </div>
          );
        })}
        <div className="options flex">
          <button onClick={createProfile}>Create New</button>
        </div>
      </div>
      <div className="setting">
        <label>Nostr Relays</label>
        {Object.keys(relays).map((r) => (
          // TODO: add connect button to connect and disc to relay one by one
          <div className="options flex" key={r}>
            <div>{r}</div>
            <button onClick={() => removeRelay(r)}>x</button>
          </div>
        ))}
        <div className="options flex">
          <label>Add new</label>
          <input
            type="text"
            value={newRelay}
            onChange={(e) => setNewRelay(e.target.value)}
          />
          <button onClick={addNewRelay}>Add</button>
        </div>
      </div>
    </div>
  );
}
export default Settings;
