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

import * as CryptoJS from 'crypto-js'
import data from "../../Data.ts"
import EventBus from "../../EventBus.ts"

interface Refs {
    addContactDialogRef: React.MutableRefObject<Dialog | null>
}

export default function AddContactDialog({
    addContactDialogRef,
}: Refs) {
    const inputTargetRef = React.useRef<TextField>(null)

    async function addContact() {
        const re = await Client.invoke("User.addContacts", {
            targets: [inputTargetRef.current!.value],
            token: data.access_token,
        })

        if (checkApiSuccessOrSncakbar(re, "添加失敗")) return
        snackbar({
            message: re.msg,
            placement: "top",
        })
        EventBus.emit('ContactsList.updateContacts')

        inputTargetRef.current!.value = ''
        addContactDialogRef.current!.open = false
    }

    return (
        <mdui-dialog close-on-overlay-click close-on-esc headline="添加对话" ref={addContactDialogRef}>
            <mdui-text-field clearable label="对话 ID / 用户 ID / 用户名" ref={inputTargetRef as any} onKeyDown={(event) => {
                if (event.key == 'Enter')
                    addContact()
            }}></mdui-text-field>
            <mdui-button slot="action" variant="text" onClick={() => addContactDialogRef.current!.open = false}>取消</mdui-button>
            <mdui-button slot="action" variant="text" onClick={() => addContact()}>添加</mdui-button>
        </mdui-dialog>
    )
}