import { EditorProperties, getDefaultValue, Infer } from "@iplusplus/y-model"
import React from "react"
import { GetUserDataFunction, userInteractionInternals } from "./userInteraction"
import { PropertyGridDialog } from "../propertygrid"
import { checkCanEdit } from "../convention"

type UserDataInfo<T extends EditorProperties> = {
  title?: string
  props: T
  resolve: (data: Infer<T> | undefined) => void
  initialData?: Infer<T>
}

export const UserDataDialog = React.memo(function () {
  const [userDataInfo, setUserDataInfo] = React.useState<UserDataInfo<EditorProperties>>()

  React.useEffect(() => {
    const getUserData: GetUserDataFunction = (title, props, initialData) => {
      return new Promise(resolve => {
        setUserDataInfo({ title, props, resolve, initialData })
      })
    }
    userInteractionInternals.getUserDataFromDialog = getUserData
    return () => (userInteractionInternals.getUserDataFromDialog = undefined)
  }, [setUserDataInfo])

  if (!userDataInfo) return null
  const disableEditFields = userDataInfo.props.filter(p => !checkCanEdit(p)).map(p => p.name)
  return (
    <PropertyGridDialog
      open={true}
      data={userDataInfo.initialData || getDefaultValue(userDataInfo.props)}
      onClose={data => {
        userDataInfo.resolve(data)

        setUserDataInfo(undefined)
      }}
      disableEditFields={disableEditFields}
      props={userDataInfo.props}
      title={userDataInfo.title}
    />
  )
})
