import styled from "@emotion/styled";
import React, { useEffect, useMemo, useRef } from "react";
import { LIGHT_SECONDARY_ONE } from "../../../shared/colors";

type Props = {
  value: string;
  onChange: (value: string) => any;
  placeholder?: string;
  autoFocus?: boolean;
  onBlur?: (e: React.FocusEvent<HTMLDivElement>) => any;
  onKeyDown?: (e: React.KeyboardEvent<HTMLDivElement>) => any;
  onKeyPress?: (e: React.KeyboardEvent<HTMLDivElement>) => any;
  style?: any;
};

function ContentEditableDiv(props: Props) {
  const ref = useRef<HTMLDivElement>(null);
  const {
    value,
    onChange,
    placeholder,
    style,
    onBlur,
    onKeyPress,
    onKeyDown,
    ...otherProps
  } = props;
  useEffect(() => {
    if (props.autoFocus) {
      ref.current!.focus();
      const range = document.createRange();
      range.selectNodeContents(ref.current!);
      range.collapse(false);
      const sel = window.getSelection()!;
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }, []);

  return useMemo(
    () => (
      <ContentEditable
        {...otherProps}
        ref={ref}
        contentEditable
        onInput={(e) => props.onChange(ref.current!.innerText)}
        dataText={placeholder || ""}
        placeholder={placeholder}
        suppressContentEditableWarning
        style={style}
        onBlur={onBlur}
        onKeyPress={onKeyPress}
        onKeyDown={onKeyDown}
      >
        {value}
      </ContentEditable>
    ),
    []
  );
}

export default ContentEditableDiv;

const ContentEditable = styled.div<{ dataText: string }>`
  :active {
    outline: none;
  }
  :focus {
    outline: none;
  }
  caret-color: ${LIGHT_SECONDARY_ONE};
  :empty {
    background-color: #ff0000;
    color: gray;
  }
`;
