import { useRef } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { updateDatabase } from '../database/database'
import styled from 'styled-components'
import ContentEditable from 'react-contenteditable'

const StyledContentEditable = styled(ContentEditable)`
  ${props => props.$sty}
`

function Editable({ props }) {
  const database = useSelector((state) => state.database.value);
  const dispatch = useDispatch();

  const content = useRef(props.content);

  const handleChange = evt => {
    content.current = evt.target.value;
  };

  const handleBlur = () => {
    const newParams = { ...database[id], content: content.current };
    const newDatabase = { ...database, [id]: newParams };
    dispatch(updateDatabase(newDatabase));
  }

  const handlePaste = (evt) => {
    evt.preventDefault();
    const copyText = (evt.originalEvent || evt).clipboardData.getData('text/plain');
    document.execCommand("insertHTML", false, copyText);
  }

  const style = props.styles;

  return (
    <>
      <StyledContentEditable
        html={content.current}
        onBlur={handleBlur}
        onChange={handleChange}
        onPaste={handlePaste}
        tagName={props.tagName}
        className={'ld-item ' + props.className}
        id={props.id}
        $sty={style}
      />
    </>
  )
}

export default Editable