import { EditorProperty } from "@iplusplus/y-model"
import { ColorPicker, IColor, useColor } from "react-color-palette"

import "react-color-palette/css"
import { GridCellEditStopReasons, useGridApiContext } from "@mui/x-data-grid"
import { Box, Popper } from "@mui/material"
import { useEffect, useRef, useState } from "react"
import { CellRender, CellRenderBuilder2, CellRenderParam } from "../types"
import ClearIcon from '@mui/icons-material/Clear';
import { CustomIcon } from "../../ui-utils"


export function ColorSelectCell({ cellParams, property }: { cellParams: CellRenderParam, property: EditorProperty }) {
  const { id, value, field } = cellParams

  const divRef = useRef<HTMLDivElement>(null)
  const apiRef = useGridApiContext()

  const [showPops, setShowPops] = useState(false)
  //  console.log(value);
  const [color, setColor] = useColor(value as unknown as string)
  const colorChange = (newColor: IColor) => {
    apiRef.current.setEditCellValue({ id, field, value: newColor.hex })
    setColor(newColor)
  }

  useEffect(() => {
    //  console.log(divRef.current)
    setShowPops(true)
  }, [])
  //const needShowPops = divRef.current != null && showPops
  //  console.log(value)
  const enableClear = property.valueType.getAttach("canBeEmpty")
  const onClear = () => {
    apiRef.current.setEditCellValue({ id, field, value: "" })
    setShowPops(false)
    apiRef.current.publishEvent("cellEditStop", {
      ...cellParams,
      reason: GridCellEditStopReasons.cellFocusOut,
    })
  }
  const clearButton = enableClear ? <CustomIcon icon={<ClearIcon />} handler={onClear} /> : null

  return (
    <div>
      <div ref={divRef}>
        <span>请选择</span>
        {clearButton}
      </div>
      <Popper open={showPops} anchorEl={divRef.current} sx={{ zIndex: 2000 }}>
        <Box sx={{ width: 300, backgroundColor: "white" }}>
          <ColorPicker hideInput={["rgb", "hsv"]} color={color} onChange={colorChange} />
        </Box>
      </Popper>
    </div>
  )
}

// const colorEditRender: CellRender = params => {
//   return <ColorSelectCell cellParams={params} />
// }

function renderColorEditRender(property: EditorProperty): CellRender {
  return params => {
    return <ColorSelectCell cellParams={params} property={property} />
  }
}

const colorRender: CellRender = params => {
  //    console.log(params.value)


  if (params.value) {
    return <div style={{ display: "flex", alignItems: "center" }}>
      <div style={{ width: "16px", height: "16px", backgroundColor: params.value }}></div>
      <div>[{params.value}]</div>
    </div>
  }
  return <div></div>
}

export const colorRenderBuilder: CellRenderBuilder2 = (property: EditorProperty) => {
  if (property.editorType === "color") {
    return {
      editorCellRender: renderColorEditRender(property),
      cellRender: colorRender,
    }
  }

  return undefined
}
