import { useState, type ChangeEvent, type FormEvent, useEffect } from "react";
import Form from "~components/ui/form";
import { IconPaul } from "~assets/icons";
import Message from "~components/ui/message";
import { add } from "~components/ui/message/utils";
import "~assets/global.css";
import styles from "./options.module.less";

function Options() {
  const [state, setState] = useState({
    token: "",
    siteUrl: "",
  });

  useEffect(() => {
    chrome.storage.local.get(["token", "siteUrl"]).then((res) => {
      setState((prevState) => ({ ...prevState, ...(res as any)}));
    });
  }, []);

  const onChange = (ev: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = ev.target;

    if (!name) {
      return;
    }

    setState((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  }

  const onSubmit = (ev: FormEvent) => {
    ev.preventDefault();

    chrome.storage.local.set(state);

    add({
      content: "保存成功",
    });
  }

  return (
    <>
      <div className={styles.options} onSubmit={onSubmit}>
        <h1 className={styles.title}>
          <IconPaul />
          小窝工具箱 设置面板
        </h1>
        <Form className={styles.form}>
          <div>
            <label htmlFor="token">后端通信 Token</label>
            <input id="token" name="token" value={state.token} onChange={onChange} />
          </div>
          <div>
            <label htmlFor="siteUrl">后端 API 地址</label>
            <input id="siteUrl" name="siteUrl"
              placeholder="不包含 /api"
              value={state.siteUrl} onChange={onChange}
            />
          </div>

          <button type="submit">保存</button>
        </Form>
      </div>
      <Message />
    </>
  );
}

export default Options;
