import { EditorProperty } from '@iplusplus/y-model';

import { GridRenderCellParams, useGridApiContext } from "@mui/x-data-grid";

import React from "react";
import dayjs, { Dayjs } from "dayjs";
import CustomDateTimePicker from '../../ui-utils/CustomDateTimePicker';
import { CellRender, CellRenderBuilder2 } from '../types';
import { timeUtils } from '../../utils/time';

function CustomTimePicker({ cellParams }: {
  cellParams: GridRenderCellParams<any, Record<string, any>[]>
}) {
  const apiRef = useGridApiContext();

  const { id, value, field } = cellParams;

  const timestamp = value as unknown as number
  const dd = dayjs(timestamp);
  const [value2, setValue] = React.useState<Dayjs>(dd);
  return <CustomDateTimePicker
    views={['year', 'month', 'day', 'hours', 'minutes', 'seconds']}
    value={value2}
    onChange={(newView => {
      if (newView) {
        apiRef.current.setEditCellValue({ id, field, value: newView.toDate().getTime() });
      }
      setValue(newView);
    })} />;
}

const xx: CellRender = (params) => {
  return <CustomTimePicker cellParams={params} />
}


const xx2: CellRender = (params) => {
  const v = params.value as number;
  return <div>{timeUtils.timestampToTimeString(v)}</div>
}



export const timestampRenderBuilder: CellRenderBuilder2 = (property: EditorProperty) => {


  if (property.editorType === "timestamp") {

    return {
      editorCellRender: xx,
      cellRender: xx2
    }
  }



  return undefined;
}