import { memo, useEffect, useState } from "react"
import { GetUserConfirmFunction, userInteractionInternals } from "./userInteraction"
import { Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions, Button } from "@mui/material"

type UserConfirmInfo2 = {
  title?: string
  content: string
  resolve: (data: boolean) => void
}

const UserConfirmDialog = memo(() => {
  const [userConfirmInfo, setUserConfirmInfo] = useState<UserConfirmInfo2>()

  useEffect(() => {
    const getUserConfirm: GetUserConfirmFunction = info => {
      return new Promise(resolve => {
        setUserConfirmInfo({ ...info, resolve })
      })
    }
    userInteractionInternals.getUserConfirm = getUserConfirm
    return () => (userInteractionInternals.getUserConfirm = undefined)
  })

  if (!userConfirmInfo) return null
  const onClose = () => {
    userConfirmInfo.resolve(false)
    setUserConfirmInfo(undefined)
  }
  const onOk = () => {
    userConfirmInfo.resolve(true)
    setUserConfirmInfo(undefined)
  }

  return (
    <Dialog open={true} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>{userConfirmInfo.title || "确认"}</DialogTitle>
      <DialogContent>
        <DialogContentText>{userConfirmInfo.content}</DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>取消</Button>
        <Button onClick={onOk} autoFocus>
          确定
        </Button>
      </DialogActions>
    </Dialog>
  )
})

export default UserConfirmDialog
