import {
  GridEditSingleSelectCellProps,
  useGridApiContext,
  GridEditSingleSelectCell,
  GridSingleSelectColDef,
  GridCellEditStopReasons,
} from "@mui/x-data-grid"
import { GridStateColDef } from "@mui/x-data-grid/internals"
import { CellRenderParam } from "../../types"
import { KeyValueItem } from "./types"

function CustomTypeEditComponent(props: GridEditSingleSelectCellProps) {
  const apiRef = useGridApiContext()

  const { id, field } = props
  return (
    <GridEditSingleSelectCell
      {...props}
      onValueChange={(_e, v) => {
        // apiRef.current.stopCellEditMode({id, field})
        apiRef.current.setEditCellValue({ id, field, value: v })
        apiRef.current.publishEvent("cellEditStop", {
          ...props,
          reason: GridCellEditStopReasons.cellFocusOut,
        })
      }}
    />
  )
}

export function CellEnumSelectList({ items, params }: { items: KeyValueItem[]; params: CellRenderParam }) {
  const { colDef } = params
  const newColDef: GridSingleSelectColDef = { ...colDef, type: "singleSelect" }
  newColDef.valueOptions = items.map(item => item[0])
  newColDef.getOptionLabel = value => {
    //     console.log("getOptionLabel",value)
    const r = items.find(item => (item[0] === value) || (value===undefined && item[0]==="undefined") )
    return r ? r[1] : ""
  }
  newColDef.getOptionValue = value => {
    if(value==="undefined") return undefined
    return value
  }
  return <CustomTypeEditComponent {...params} colDef={newColDef as GridStateColDef} />
}
