import { type FC, useEffect, useState } from 'react';

import { EditorContent, useEditor } from '@tiptap/react';
import Box from '@material-hu/mui/Box';
import { type SxProps } from '@material-hu/mui/styles';

import { ButtonText } from 'src/pages/dashboard/feed/components/ButtonText';
import { highlightTextInHTML, truncateHTML } from 'src/utils/feed';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { capitalizeFirstLetter } from 'src/utils/text';

import useExtensions from './hooks/useExtensions';
import { StyledContainer } from '.';

type ReadOnlyProps = {
  content: string;
  maxCharacters: number;
  maxNewLines: number;
  withShowMoreButton?: boolean;
  sxContainer?: SxProps;
  onShowMore?: () => void;
  onShowLess?: () => void;
  showSeeMoreButton?: boolean;
  matchText?: string;
};

const ReadOnly: FC<ReadOnlyProps> = props => {
  const {
    content,
    maxCharacters,
    maxNewLines,
    withShowMoreButton = true,
    sxContainer = {},
    onShowMore,
    onShowLess,
    showSeeMoreButton,
    matchText,
  } = props;

  const [showMore, setShowMore] = useState(true);

  const extensions = useExtensions();
  const { t } = useLokaliseTranslation();

  // Apply highlighting if matchText is provided
  const highlightedContent = matchText
    ? highlightTextInHTML(content, matchText)
    : content;

  const editor = useEditor({
    extensions,
    content: highlightedContent,
    editable: false,
  });

  const { htmlTruncated, isTruncated } = truncateHTML(
    highlightedContent,
    maxCharacters,
    maxNewLines,
  );

  useEffect(() => {
    if (editor) {
      editor.commands.setContent(showMore ? htmlTruncated : highlightedContent);
    }
  }, [editor, showMore, htmlTruncated, highlightedContent, matchText]);

  const handleShow = () => {
    setShowMore(!showMore);
    if (showMore) {
      onShowMore?.();
    } else {
      onShowLess?.();
    }
  };

  return (
    <StyledContainer
      sx={{
        position: 'relative',
        ...sxContainer,
      }}
      isReadOnly
    >
      <EditorContent editor={editor} />
      {((withShowMoreButton && isTruncated) || showSeeMoreButton) && (
        <Box sx={{ mb: 2 }}>
          <ButtonText
            variant="text"
            onClick={handleShow}
            sx={{
              cursor: 'pointer',
              marginLeft: '5px',
              position: 'absolute',
              right: 0,
              bottom: -16,
              minWidth: 'auto',
            }}
          >
            {capitalizeFirstLetter(t(showMore ? 'SEE_MORE' : 'SEE_LESS'))}
          </ButtonText>
        </Box>
      )}
    </StyledContainer>
  );
};

export default ReadOnly;
