import { useMemo } from 'react';
import { Room } from 'matrix-js-sdk';
import { HTMLReactParserOptions } from 'html-react-parser';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { useMentionClickHandler } from '../../hooks/useMentionClickHandler';
import { useSpoilerClickHandler } from '../../hooks/useSpoilerClickHandler';
import {
  LINKIFY_OPTS,
  factoryRenderLinkifyWithMention,
  getReactCustomHtmlParser,
  makeMentionCustomProps,
  renderMatrixMention,
} from '../../plugins/react-custom-html-parser';
import {
  combineEmbedFilters,
  useRoomEmbedFilters,
  useRoomWideEmbedFilters,
} from '../../hooks/useRoomEmbedFilters';
import { useSetting } from '../../state/hooks/settings';
import { MessageLayout, settingsAtom } from '../../state/settings';

export function useForumMessageRenderOptions(room: Room | null | undefined) {
  const mx = useMatrixClient();
  const useAuthentication = useMediaAuthentication();
  const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad');
  const [showUrlPreview] = useSetting(settingsAtom, 'urlPreview');
  const [messageLayout] = useSetting(settingsAtom, 'messageLayout');

  const [personalEmbedFilters] = useRoomEmbedFilters(room ?? undefined);
  const roomWideEmbedFilters = useRoomWideEmbedFilters(room ?? undefined);
  const combinedEmbedFilters = useMemo(
    () => combineEmbedFilters(personalEmbedFilters, roomWideEmbedFilters),
    [personalEmbedFilters, roomWideEmbedFilters]
  );

  const mentionClickHandler = useMentionClickHandler(room?.roomId ?? '');
  const spoilerClickHandler = useSpoilerClickHandler();

  const linkifyOpts = useMemo<LinkifyOpts>(
    () => ({
      ...LINKIFY_OPTS,
      render: factoryRenderLinkifyWithMention((href) =>
        renderMatrixMention(mx, room?.roomId ?? '', href, makeMentionCustomProps(mentionClickHandler))
      ),
    }),
    [mx, room?.roomId, mentionClickHandler]
  );

  const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
    () =>
      getReactCustomHtmlParser(mx, room?.roomId ?? '', {
        linkifyOpts,
        useAuthentication,
        handleSpoilerClick: spoilerClickHandler,
        handleMentionClick: mentionClickHandler,
      }),
    [mx, room?.roomId, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication]
  );

  return {
    linkifyOpts,
    htmlReactParserOptions,
    mediaAutoLoad,
    showUrlPreview,
    outlineAttachment: messageLayout === MessageLayout.Bubble,
    disabledEmbedPatterns: combinedEmbedFilters,
  };
}
