import { useState, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';

import DOMPurify from 'dompurify';
import Box from '@material-hu/mui/Box';
import FormControl from '@material-hu/mui/FormControl';
import Typography from '@material-hu/mui/Typography';

import { TaggedUser } from 'src/types/user';
import { transformTagInStrongElement } from 'src/utils/feed';

export type HighlighterProps = {
  textAreaRef?: string;
  taggedUsers: TaggedUser[];
  styles?: any;
};

const Highlighter = ({
  textAreaRef = '',
  taggedUsers = [],
  styles,
}: HighlighterProps) => {
  const [widthInput, setWidthInput] = useState(0);

  const { watch } = useFormContext();

  const body = watch('body');

  const input = document.getElementById(textAreaRef) as HTMLInputElement;

  useEffect(() => {
    if (input) {
      setWidthInput(input?.offsetWidth);
    }
  }, [input]);

  useEffect(() => {
    const handleResize = () => {
      if (input) {
        setWidthInput(input?.offsetWidth);
      }
    };
    window?.addEventListener('resize', handleResize);
    return () => {
      window?.removeEventListener('resize', handleResize);
    };
  }, [input]);

  return (
    <FormControl
      sx={{
        position: 'absolute',
        width: widthInput + 14,
        ...styles,
      }}
    >
      <Box
        sx={{
          fontWeight: '400',
          fontSize: '1rem',
          lineHeight: '1.4375em',
          color: 'transparent',
          boxSizing: ' border-box',
          cursor: 'text',
          width: 'inherit',
          position: 'relative',
          borderRadius: '16px',
          padding: '8.5px 0 8.5px 14px',
          fontFamily:
            '"Twemoji Country Flags",-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',
        }}
      >
        <Typography
          style={{
            whiteSpace: 'pre-wrap',
            overflow: 'hidden',
            wordBreak: 'break-word',
            width: 'inherit',
            overflowWrap: 'break-word',
            wordSpacing: 'normal',
            lineHeight: '1.4375em',
            color: 'transparent',
          }}
          dangerouslySetInnerHTML={{
            __html: DOMPurify.sanitize(
              transformTagInStrongElement(body, taggedUsers),
              {
                USE_PROFILES: { html: true },
              },
            ),
          }}
        />
      </Box>
    </FormControl>
  );
};

export default Highlighter;
