import { cloneElement, useState } from 'react'
import { Button, Modal } from 'antd'

export default function AppButtonModal({ buttonText = 'Open Modal', open: externalOpen, children, ...props }: any) {
  const [internalOpen, setOpen] = useState(false)

  const actionOpen = (externalOpen ?? externalOpen) || internalOpen

  // 克隆子元素并注入控制函数
  const childrenWithProps = cloneElement(children, {
    setOpen: setOpen,
  })

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        {buttonText}
      </Button>
      <Modal open={actionOpen} onCancel={() => setOpen(false)} destroyOnClose {...props}>
        {childrenWithProps}
      </Modal>
    </>
  )
}
