import * as React from 'react';
import { ID, NumericFormat, ICellNN } from '../index.data';
import { ID_CELL } from '../constants';
import { IRenderer } from '../cellTypes/index.data';
import styles from './index.less';
import classnames from 'classnames';
import equals from 'fast-deep-equal';
import { CellProps } from './index.data';
import { getCellPropsNature } from './helper';
import RuntimeContext from '../RuntimeContext';

class Cell extends React.Component<CellProps> {
  context!: React.ContextType<typeof RuntimeContext>;
  static contextType = RuntimeContext;

  constructor(props: CellProps) {
    super(props);
  }

  shouldComponentUpdate(nextProps: CellProps) {
    const isEquals =
      (nextProps.cell === this.props.cell || equals(nextProps.cell, this.props.cell)) &&
      this.props.hidden === nextProps.hidden;
    return !isEquals;
  }

  render() {
    const props = this.props;
    if (!props.cell) return null;
    const { checkableConfig } = this.context!;
    const {
      id,
      rowId,
      rowspan,
      colspan,
      style,
      format,
      value,
      error,
      formulaIsAbstract,
      Renderer,
      isChecked,
      checkable,
      rowAdditions,
      locked,
      isCellSelected,
      getRow,
    } = getCellPropsNature(props.store, props.row, props.cell, checkableConfig)!;

    if (!Renderer) return null;

    return (
      <td
        key={id}
        id={`${ID_CELL}:${id}`}
        rowSpan={rowspan}
        colSpan={colspan}
        style={Object.assign({}, style, {
          overflow: props.hidden && 'hidden',
        })}
      >
        <Renderer
          id={id}
          rowId={rowId}
          value={value!}
          style={style}
          format={format}
          error={error}
          formulaIsAbstract={formulaIsAbstract}
          rowAdditions={rowAdditions}
          locked={locked}
          isCellSelected={isCellSelected}
          getRow={getRow}
        />
        {checkable && (
          <div
            className={styles['clear']}
            onClick={() => {
              checkableConfig!.onCellChecked(!isChecked, (data: Partial<ICellNN>) =>
                props.setCellData({ ...data, id }),
              );
            }}
          >
            <span className={classnames({ [styles['checked']]: isChecked })}>√</span>
          </div>
        )}
      </td>
    );
  }
}

export default Cell;
