"use client";
import { addToken } from "@/lib/actions/token";
import { Token } from "@/lib/types";
import { useEffect, useRef } from "react";
import { useFormState } from "react-dom";

export default function TokenButton({
  className,
  token,
}: {
  className?: string | undefined;
  token: Token;
}) {
  const ref = useRef<HTMLDialogElement>(null);
  const [returnType, dispatch] = useFormState(addToken, token);
  // TODO 有没有更合适的方式？
  if (returnType) {
    ref.current?.close();
  }
  return (
    <>
      <button className={className} onClick={() => ref.current?.showModal()}>
        Token 设定
      </button>
      <dialog className="modal" ref={ref}>
        <div className="modal-box">
          <h3 className="font-bold text-lg">Token 设定</h3>
          <form className="join join-vertical w-full mt-4" id="token" action={dispatch}>
            <label className="input input-bordered flex items-center gap-2 join-item">
              陌陌 ID
              <input type="text" className="grow" name="uid" defaultValue={token.uid} />
            </label>
            <label className="input input-bordered flex items-center gap-2 join-item">
              陌陌 token
              <input type="text" className="grow" name="token" defaultValue={token.token} />
            </label>
          </form>
          <div className="modal-action">
            <form method="dialog">
              <button className="btn">关闭</button>
            </form>
            <button className="btn" form="token">
              保存
            </button>
          </div>
        </div>
        <form method="dialog" className="modal-backdrop">
          <button>关闭</button>
        </form>
      </dialog>
    </>
  );
}
