import { useEffect, useRef } from "react";
import { sendToBackground } from "@plasmohq/messaging";
import useForm from "~hooks/useForm";
import Tab from "~components/ui/tab";
import Form from "~components/ui/form";
import { add } from "~components/ui/message/utils";

interface FormValue {
  content: string;
  author: string;
  origin: string;
  links: string;
  is_comment: boolean;
}

const submitForm = (body: FormValue) => {
  sendToBackground({
    name: "say",
    body: {
      action: "addSay",
      values: body,
    },
  }).then((res) => {
    add({
      content: res.msg,
    });
  }).catch((e) => {
    if (e instanceof Error) {
      add({
        content: e.message,
      });
    }
  });
}

function Say() {
  const formRef = useRef<HTMLFormElement>();

  const { bindInput, onSubmit } = useForm<FormValue>({
    initialValues: {
      is_comment: true,
    },
  });

  return (
    <Tab>
      <Tab.Body>
        <Form ref={formRef} onSubmit={onSubmit(submitForm)}>
          <div>
            <label htmlFor="content">内容</label>
            <textarea {...bindInput("content")} rows={5} required placeholder="内容"></textarea>
          </div>
          <div>
            <label htmlFor="author">作者</label>
            <input {...bindInput("author")} placeholder="作者" />
          </div>
          <div>
            <label htmlFor="links">链接</label>
            <input {...bindInput("links")} placeholder="链接" />
          </div>
          <div>
            <label htmlFor="is_comment">摘抄</label>
            <input type="checkbox" role="switch" {...bindInput("is_comment")} placeholder="摘抄" />
          </div>
        </Form>
      </Tab.Body>
      <Tab.Footer>
        <button onClick={() => formRef.current?.requestSubmit()}>提交</button>
      </Tab.Footer>
    </Tab>
  );
}

export default Say;
