import { memo, useEffect, useState } from "react"
import { GetUserInputValueFunction, userInteractionInternals } from "./userInteraction"
import { DraggableDialog } from "../ui-utils"
import { TextField } from "@mui/material"

type UserInputValueInfo2 = {
  title?: string
  isPassword?: boolean
  defualtValue?: string
  multiline ?:boolean
  resolve: (data: string | undefined) => void
}

const UserInputValueDialog = memo(() => {
  const [userInputValueInfo, setUserInputValueInfo] = useState<UserInputValueInfo2>()
  const [value, setValue] = useState("")

  useEffect(() => {
    const getUserInputValue: GetUserInputValueFunction = info => {
      return new Promise(resolve => {
        setUserInputValueInfo({ ...info, resolve })
        setValue(info.defaultValue || "")
      })
    }
    userInteractionInternals.getUserInputValue = getUserInputValue
    return () => (userInteractionInternals.getUserInputValue = undefined)
  }, [setUserInputValueInfo, setValue])
  if (!userInputValueInfo) return null

  return (
    <DraggableDialog
      title={userInputValueInfo.title}
      onCancel={() => setUserInputValueInfo(undefined)}
      onOk={() => {
        userInputValueInfo.resolve(value)
        setUserInputValueInfo(undefined)
      }}
    >
      <TextField
        type={userInputValueInfo.isPassword ? "password" : "text"}
        value={value}
        autoFocus
        margin="dense"
        fullWidth
        variant="standard"
        multiline = {userInputValueInfo.multiline}
        onChange={e => {
          setValue(e.target.value)
        }}
      />
    </DraggableDialog>
  )
})

export default UserInputValueDialog
