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

import { type Editor } from '@tiptap/react';
import { IconLink } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { type Theme } from '@material-hu/mui/styles';

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

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

import SetLinkModal from './SetLinkModal';

type SetLinkProps = {
  editor: Editor;
  commonStyles: { height: string; width: string; borderRadius: string };
  activeStyles: (theme: Theme) => {
    backgroundColor: string;
    color: string;
  };
  TooltipComponent: FC<TooltipProps>;
};

const SetLink: FC<SetLinkProps> = props => {
  const { editor, commonStyles, activeStyles, TooltipComponent } = props;
  const [open, setOpen] = useState(false);
  const closeModal: () => void = () => setOpen(false);

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

  if (!editor) {
    return null;
  }

  return (
    <Stack>
      <SetLinkModal
        open={open}
        onClose={closeModal}
        editor={editor}
      />
      <TooltipComponent title={t('top_bar_rich_text_editor.link')}>
        <IconButton
          onClick={() => setOpen(true)}
          disabled={editor.isActive('code')}
          sx={theme => ({
            ...commonStyles,
            ...(editor.isActive('link') && activeStyles(theme)),
          })}
        >
          <IconLink />
        </IconButton>
      </TooltipComponent>
    </Stack>
  );
};

export default SetLink;
