import * as React from 'react'
import { Button, Dialog, TextField } from "mdui";
import useEventListener from "../useEventListener.ts";
import Client from "../../api/Client.ts";
import { checkApiSuccessOrSncakbar, snackbar } from "../snackbar.ts";

import * as CryptoJS from 'crypto-js'

interface Refs {
    loginInputAccountRef: React.MutableRefObject<TextField | null>
    loginInputPasswordRef: React.MutableRefObject<TextField | null>
    registerInputUserNameRef: React.MutableRefObject<TextField | null>
    registerInputNickNameRef: React.MutableRefObject<TextField | null>
    registerInputPasswordRef: React.MutableRefObject<TextField | null>
    registerDialogRef: React.MutableRefObject<Dialog | null>
}

export default function RegisterDialog({
    loginInputAccountRef,
    loginInputPasswordRef,
    registerInputUserNameRef,
    registerInputNickNameRef,
    registerInputPasswordRef,
    registerDialogRef
}: Refs) {
    const registerBackButtonRef = React.useRef<Button>(null)
    const doRegisterButtonRef = React.useRef<Button>(null)
    useEventListener(registerBackButtonRef, 'click', () => registerDialogRef.current!.open = false)
    useEventListener(doRegisterButtonRef, 'click', async () => {
        const username = registerInputUserNameRef.current!.value
        const re = await Client.invoke("User.register", {
            username: username,
            nickname: registerInputNickNameRef.current!.value,
            password: CryptoJS.SHA256(registerInputPasswordRef.current!.value).toString(CryptoJS.enc.Hex),
        })

        if (checkApiSuccessOrSncakbar(re, "注册失败")) return
        loginInputAccountRef.current!.value = username == "" ? re.data!.userid as string : username
        loginInputPasswordRef.current!.value = registerInputPasswordRef.current!.value

        registerInputUserNameRef.current!.value = ""
        registerInputNickNameRef.current!.value = ""
        registerInputPasswordRef.current!.value = ""
        registerDialogRef.current!.open = false
        snackbar({
            message: "注册成功!",
            placement: "top",
        })
    })
    return (
        <mdui-dialog headline="注册" ref={registerDialogRef}>

            <mdui-text-field label="用户名 (可选)" ref={registerInputUserNameRef as any}></mdui-text-field>
            <div style={{
                height: "10px",
            }}></div>
            <mdui-text-field label="昵称" ref={registerInputNickNameRef as any}></mdui-text-field>
            <div style={{
                height: "10px",
            }}></div>
            <mdui-text-field label="密码" type="password" toggle-password ref={registerInputPasswordRef as any}></mdui-text-field>

            <mdui-button slot="action" variant="text" ref={registerBackButtonRef}>返回</mdui-button>
            <mdui-button slot="action" variant="text" ref={doRegisterButtonRef}>注册</mdui-button>
        </mdui-dialog>
    )
}