import { EditorProperties } from "@iplusplus/y-model"
import { useState } from "react"

import { Button, Dialog, DialogActions, DialogContent, DialogTitle } from "@mui/material"
import { produce } from "immer"
import { getPropertyGridValues } from "./types"
import React from "react"
import { PropertyGrid } from "./PropertyGrid"

export const PropertyGridDialog = React.memo(function ({
  open,
  onClose,
  data,
  props,
  title,
  disableEditFields,
}: {
  open: boolean
  onClose: (value?: Record<string, unknown>) => void
  data: Record<string, unknown>
  props: EditorProperties
  disableEditFields?: string[]
  title?: string
}) {
  const [currentData, setCurrentData] = useState(data)
  const [disableSubmit, setDisableSubmit] = useState(false)
  const [isSubmiting, setIsSubmiting] = useState(false)
  const handleCancel = () => {
    onClose()
  }

  const handleOk = () => {
    setIsSubmiting(true)
    onClose({ ...currentData })
    // setIsSubmiting(false);
  }
  const onEditStateNotify = (isInEdit: boolean) => {
    setDisableSubmit(isInEdit)
  }
  const values = getPropertyGridValues(currentData, props)
  return (
    <Dialog open={open} keepMounted maxWidth={"sm"} fullWidth={true}>
      <DialogTitle>{title || "编辑清单属性"}</DialogTitle>
      <DialogContent dividers>
        <PropertyGrid
          disableEditFields={disableEditFields}
          values={values}
          onNewValueSubmit={(prop, value) => {
            const newData = produce(currentData, draft => {
              draft[prop.name] = value
            })
            setCurrentData(newData)
          }}
          onEditStateNotify={onEditStateNotify}
        />
      </DialogContent>
      <DialogActions>
        <Button autoFocus onClick={handleCancel}>
          取消
        </Button>
        <Button disabled={disableSubmit || isSubmiting} onClick={handleOk}>
          {isSubmiting ? "正在提交" : "确定"}
        </Button>
      </DialogActions>
    </Dialog>
  )
})
