import { GridCellEditStopReasons, useGridApiContext } from "@mui/x-data-grid"
import { EditorProperty, ObjectValueType, fillDefaultValue } from "@iplusplus/y-model"

import { useState } from "react"
import { PropertyGridDialog } from "../../propertygrid"
import { CellRender, CellRenderBuilder2, CellRenderParam } from "../types"

function PropertyGridDialogCell({
  cellParams,
  objectType,
}: {
  cellParams: CellRenderParam
  objectType: ObjectValueType<unknown>
}) {
  const { id, value, field } = cellParams
  const apiRef = useGridApiContext()
  //  const ref = React.useRef<HTMLElement>();
  const [open, setOpen] = useState(true)

  const onClose = (data?: Record<string, unknown>) => {
    setOpen(false)
    apiRef.current.stopCellEditMode({
      id,
      field,
    })

    if (data) {
      apiRef.current.setEditCellValue({ id, field, value: data })
    }
    apiRef.current.publishEvent("cellEditStop", {
      ...cellParams,
      reason: GridCellEditStopReasons.cellFocusOut,
    })
  }

  const v2 = fillDefaultValue(objectType.subProperty, value)
  // console.log("render ObjectArrayEditorDialog")
  return open ? <PropertyGridDialog open={open} props={objectType.subProperty} data={v2} onClose={onClose} /> : null
}

// export function createObjectEditRender<T extends EditorProperties>(objectType: ObjectType<T>):EditCellRender{
//     return (params)=>{
//         return <PropertyGridDialogCell cellParams={params} objectType={objectType} />
//     }
// }

// // export

function createObjectEditRender(objectType: ObjectValueType<unknown>): CellRender {
  return params => {
    return <PropertyGridDialogCell cellParams={params} objectType={objectType} />
  }
}

function createObjectRender(objectType: ObjectValueType<unknown>): CellRender {
  return params => {
    const { value } = params
    return <div>{objectType.showString(value)} </div>
  }
}

export const objectRenderBuilder: CellRenderBuilder2 = (property: EditorProperty) => {
  if (property.valueType.dataTypeName === "object") {
    const vt = property.valueType

    return {
      editorCellRender: createObjectEditRender(vt),
      cellRender: createObjectRender(vt),
    }
  }

  return undefined
}
