import { useState, 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";
import Placeholder from "~components/ui/placeholder";

import styles from "./toy.module.less";

interface FormValue {
  name: string;
  ename: string;
  project: string;
  made: string;
  sale: string;
  type: number;
  desc: string;
  productId: string;
}

const getInfo = async () => {
  let tab: chrome.tabs.Tab;

  [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });

  if (tab && !tab.url.includes("chrome")) {
    return await chrome.tabs.sendMessage(tab.id, { type: 'toolbox:getBiliToy' });
  }
}

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

  const { bindInput, setValues, onSubmit } = useForm<FormValue>({
    initialValues: {
      type: 3,
    },
  });

  const [imgs, setImgs] = useState([]);
  const [currentImg, setCurrentImg] = useState(0);

  const submitForm = (body: FormValue) => {
    sendToBackground({
      name: "toy",
      body: {
        action: "addToy",
        values: {
          ...body,
          imageUrl: imgs[0],
        },
      },
    }).then((res) => {
      add({
        content: res.msg,
      });
    }).catch((e) => {
      if (e instanceof Error) {
        add({
          content: e.message,
        });
      }
    });
  }

  useEffect(() => {
    getInfo().then((res) => {
      if (!res) {
        return;
      }

      const { images, ...others } = res;

      setImgs(images);
      setCurrentImg(0);

      // ! 必须等组件渲染出来才能设置值，这里是个问题
      window.requestAnimationFrame(() => {
        setValues(others);
      });
    })
  }, []);

  return (
    <Placeholder className={styles.bili} show={imgs.length === 0} value="非 B 站会员购页面">
      <Tab>
        <Tab.Body>
          <div className={styles.image}>
            <img src={imgs[currentImg]} alt="" />
            <div className={styles.selector}>
              {imgs.map((item, index) => (
                <img key={index} src={item} alt="" onClick={() => setCurrentImg(index)} />
              ))}
            </div>
          </div>
          <Form ref={formRef} className={styles.form} onSubmit={onSubmit(submitForm)}>
            <div>
              <label htmlFor="name">中文名</label>
              <input {...bindInput("name")} required placeholder="中文名" />
            </div>
            <div>
              <label htmlFor="ename">英文名</label>
              <input {...bindInput("ename")} placeholder="英文名" />
            </div>
            <div>
              <label htmlFor="project">作品</label>
              <input {...bindInput("project")} placeholder="作品" />
            </div>
            <div>
              <label htmlFor="made">制作</label>
              <input {...bindInput("made")} placeholder="制作" />
            </div>
            <div>
              <label htmlFor="sale">发售日期</label>
              <input {...bindInput("sale")} placeholder="发售日期" />
            </div>
            <div>
              <label htmlFor="type">状态</label>
              <select {...bindInput("type")} required>
                <option value={1}>已到货</option>
                <option value={2}>已预订</option>
                <option value={3}>想要但没钱</option>
              </select>
            </div>
            <div>
              <label htmlFor="productId">B 站产品 ID</label>
              <input {...bindInput("productId")} placeholder="B 站产品 ID" />
            </div>
            <div>
              <label htmlFor="desc">描述</label>
              <textarea {...bindInput("desc")} rows={5} placeholder="描述"></textarea>
            </div>
          </Form>
        </Tab.Body>
        <Tab.Footer>
          <button onClick={() => formRef.current?.requestSubmit()}>提交</button>
        </Tab.Footer>
      </Tab>
    </Placeholder>
  );
}

export default Toy;
