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

import { type Editor } from '@tiptap/react';
import {
  IconBold,
  IconCode,
  IconItalic,
  IconList,
  IconListNumbers,
  IconQuote,
  IconStrikethrough,
  IconUnderline,
} from '@material-hu/icons/tabler';
import Collapse from '@material-hu/mui/Collapse';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { type Theme, useTheme } from '@material-hu/mui/styles';

import HuTooltip from '@material-hu/components/design-system/Tooltip';
import {
  type MUITooltipProps,
  type TooltipProps,
} from '@material-hu/components/design-system/Tooltip/types';

import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import ReactionAdd from 'src/components/dashboard/reactions/ReactionAdd';

import { type ToolbarOptions } from '../types';

import HeadingMenu from './HeadingMenu';
import SetLink from './SetLink';

export type TopBarProps = {
  editor: Editor;
  toolbarOptions: ToolbarOptions;
};

const commonStyles = {
  height: '24px',
  width: '24px',
  borderRadius: '8px',
  padding: '4px',
  color: (theme: Theme) => theme.palette.new.text.neutral.lighter,
};

const activeStyles = (theme: Theme) => ({
  backgroundColor: theme.palette.new.background.layout.tertiary,
  color: theme.palette.new.text.neutral.default,
});

const tooltipCommonProps: Omit<MUITooltipProps, 'children' | 'title'> = {
  placement: 'top',
};

const TopBarTooltip: FC<TooltipProps> = props => {
  const { children, title, ...rest } = props;
  return (
    <HuTooltip
      title={title}
      {...tooltipCommonProps}
      {...rest}
    >
      <span style={{ display: 'inline-flex' }}>{children}</span>
    </HuTooltip>
  );
};

const TopBar: FC<TopBarProps> = props => {
  const { editor, toolbarOptions } = props;
  const { palette } = useTheme();
  const [isTopBarHovered, setIsTopBarHovered] = useState(false);
  const [isTopBarFocused, setIsTopBarFocused] = useState(false);
  const [isEditorFocused, setIsEditorFocused] = useState(false);

  const { t } = useTranslation('web_only');

  useEffect(() => {
    editor.on('focus', () => {
      setIsEditorFocused(true);
    });
    editor.on('blur', () => {
      setIsEditorFocused(false);
    });

    return () => {
      editor.off('focus');
      editor.off('blur');
    };
  }, [editor]);

  const collapseTopBar =
    !editor ||
    (editor.isEmpty &&
      !isEditorFocused &&
      !isTopBarHovered &&
      !isTopBarFocused);

  const handleAddEmoji = (emoji: string) =>
    editor.commands.insertContent(emoji);

  const commonProps = { editor, commonStyles, activeStyles };

  return (
    <Collapse
      in={!collapseTopBar}
      timeout={{
        enter: 200,
        exit: 600,
      }}
    >
      <Stack
        onMouseEnter={() => setIsTopBarHovered(true)}
        onMouseLeave={() => setIsTopBarHovered(false)}
        onFocus={() => setIsTopBarFocused(true)}
        onBlur={() => setIsTopBarFocused(false)}
        tabIndex={0}
        sx={theme => ({
          flexDirection: 'row',
          flexWrap: 'wrap',
          gap: 1,
          alignItems: 'center',
          backgroundColor: theme.palette.new.background.layout.default,
          borderTopRightRadius: '8px',
          borderTopLeftRadius: '8px',
          padding: '8px 12px',
          [theme.breakpoints.down('md')]: {
            gap: 0.5,
            padding: '8px 6px',
          },
        })}
      >
        {toolbarOptions.emoji && (
          <ReactionAdd
            onAdd={handleAddEmoji}
            transformOrigin={{ horizontal: 'left', vertical: 'top' }}
            anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }}
            tooltipProps={{
              ...tooltipCommonProps,
              direction: 'top',
            }}
            iconColor={palette.action?.active}
            iconProps={{
              '& button': {
                width: '24px',
                height: '24px',
                p: 0.5,
                backgroundColor: 'transparent',
              },
            }}
          />
        )}
        {toolbarOptions.bold && (
          <TopBarTooltip title={t('top_bar_rich_text_editor.bold')}>
            <IconButton
              onClick={() => editor.chain().focus().toggleBold().run()}
              disabled={!editor.can().chain().focus().toggleBold().run()}
              sx={theme => ({
                ...commonStyles,
                ...(editor.isActive('bold') && activeStyles(theme)),
              })}
            >
              <IconBold />
            </IconButton>
          </TopBarTooltip>
        )}
        {toolbarOptions.italic && (
          <TopBarTooltip title={t('top_bar_rich_text_editor.italic')}>
            <IconButton
              onClick={() => editor.chain().focus().toggleItalic().run()}
              disabled={!editor.can().chain().focus().toggleItalic().run()}
              sx={theme => ({
                ...commonStyles,
                ...(editor.isActive('italic') && activeStyles(theme)),
              })}
            >
              <IconItalic />
            </IconButton>
          </TopBarTooltip>
        )}
        {toolbarOptions.underline && (
          <TopBarTooltip title={t('top_bar_rich_text_editor.underline')}>
            <IconButton
              onClick={() => editor.chain().focus().toggleUnderline().run()}
              disabled={!editor.can().chain().focus().toggleUnderline().run()}
              sx={theme => ({
                ...commonStyles,
                ...(editor.isActive('underline') && activeStyles(theme)),
              })}
            >
              <IconUnderline />
            </IconButton>
          </TopBarTooltip>
        )}
        {toolbarOptions.strikethrough && (
          <TopBarTooltip title={t('top_bar_rich_text_editor.strike')}>
            <IconButton
              onClick={() => editor.chain().focus().toggleStrike().run()}
              disabled={!editor.can().chain().focus().toggleStrike().run()}
              sx={theme => ({
                ...commonStyles,
                ...(editor.isActive('strike') && activeStyles(theme)),
              })}
            >
              <IconStrikethrough />
            </IconButton>
          </TopBarTooltip>
        )}
        {toolbarOptions.link && (
          <SetLink
            {...commonProps}
            TooltipComponent={TopBarTooltip}
          />
        )}
        {toolbarOptions.heading && (
          <HeadingMenu
            {...commonProps}
            TooltipComponent={TopBarTooltip}
          />
        )}
        {toolbarOptions.bulletList && (
          <TopBarTooltip title={t('top_bar_rich_text_editor.bullet_list')}>
            <IconButton
              onClick={() => editor.chain().focus().toggleBulletList().run()}
              sx={theme => ({
                ...commonStyles,
                ...(editor.isActive('bulletList') && activeStyles(theme)),
              })}
            >
              <IconList />
            </IconButton>
          </TopBarTooltip>
        )}
        {toolbarOptions.orderedList && (
          <TopBarTooltip title={t('top_bar_rich_text_editor.ordered_list')}>
            <IconButton
              onClick={() => editor.chain().focus().toggleOrderedList().run()}
              sx={theme => ({
                ...commonStyles,
                ...(editor.isActive('orderedList') && activeStyles(theme)),
              })}
            >
              <IconListNumbers />
            </IconButton>
          </TopBarTooltip>
        )}
        {toolbarOptions.code && (
          <TopBarTooltip title={t('top_bar_rich_text_editor.code')}>
            <IconButton
              onClick={() => editor.chain().focus().toggleCode().run()}
              disabled={editor.isActive('link')}
              sx={theme => ({
                ...commonStyles,
                ...(editor.isActive('code') && activeStyles(theme)),
              })}
            >
              <IconCode />
            </IconButton>
          </TopBarTooltip>
        )}
        {toolbarOptions.blockquote && (
          <TopBarTooltip title={t('top_bar_rich_text_editor.blockquote')}>
            <IconButton
              onClick={() => {
                if (editor.isActive('bulletList')) {
                  editor.chain().focus().toggleBulletList().run();
                  editor.chain().focus().toggleBlockquote().run();
                  editor.chain().focus().toggleBulletList().run();
                } else if (editor.isActive('orderedList')) {
                  editor.chain().focus().toggleOrderedList().run();
                  editor.chain().focus().toggleBlockquote().run();
                  editor.chain().focus().toggleOrderedList().run();
                } else {
                  editor.chain().focus().toggleBlockquote().run();
                }
              }}
              sx={theme => ({
                ...commonStyles,
                ...(editor.isActive('blockquote') && activeStyles(theme)),
              })}
            >
              <IconQuote />
            </IconButton>
          </TopBarTooltip>
        )}
      </Stack>
    </Collapse>
  );
};

export default TopBar;
