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

import { Editor } from '@tiptap/react';

import CloseOutlined from '@material-hu/icons/material/CloseOutlined';
import Dialog from '@material-hu/mui/Dialog';
import DialogActions from '@material-hu/mui/DialogActions';
import DialogContent from '@material-hu/mui/DialogContent';
import DialogTitle from '@material-hu/mui/DialogTitle';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import TextField from '@material-hu/mui/TextField';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { getFullLink } from 'src/utils/links';

type SetLinkModalProps = {
  open: boolean;
  onClose: () => void;
  editor: Editor;
};

/*
  This component is created because the NewModal and useModal not working
  because the TopBar container not allowed click on the modal
*/

const SetLinkModal: FC<SetLinkModalProps> = props => {
  const { open, onClose, editor } = props;
  const [text, setText] = useState<string>('');
  const [link, setLink] = useState<string>('');

  const { t } = useTranslation(['web_only', 'general']);

  const onCancel = () => {
    onClose();
  };

  const onSubmit = () => {
    if (editor) {
      const fullLink = getFullLink({ link, withHttp: false });
      editor
        .chain()
        .focus()
        .extendMarkRange('link')
        .unsetLink()
        .insertContentAt(editor.state.selection, {
          type: 'text',
          text,
          marks: [
            {
              type: 'link',
              attrs: {
                href: fullLink,
                target: '_blank',
                rel: 'noopener noreferrer nofollow',
              },
            },
          ],
        })
        .run();
    }

    onClose();
  };

  useEffect(() => {
    if (editor && open) {
      const selectionText = editor.state.doc.textBetween(
        editor.state.selection.from,
        editor.state.selection.to,
        ' ',
      );

      const previousUrl = editor.getAttributes('link').href || '';

      setText(selectionText || '');
      setLink(previousUrl);
    }
  }, [editor, open]);

  return (
    <Dialog
      open={open}
      onClose={onClose}
      fullWidth
      maxWidth="xs"
    >
      <Stack sx={{ px: 4, pb: 4, pt: 3, gap: 1 }}>
        <Stack
          sx={{
            alignItems: 'center',
            justifyContent: 'space-between',
            flexDirection: 'row',
          }}
        >
          <DialogTitle
            sx={{ p: 0, mr: 'auto', flexShrink: 1, alignSelf: 'center' }}
          >
            {t('web_only:top_bar_rich_text_editor.add_link')}
          </DialogTitle>
          <IconButton
            aria-label="close"
            onClick={onClose}
            sx={{ p: 0 }}
          >
            <CloseOutlined />
          </IconButton>
        </Stack>

        <DialogContent sx={{ p: 0, height: '185px' }}>
          <Stack>
            <Typography
              variant="subtitle1"
              color="text.primary"
            >
              {t('web_only:top_bar_rich_text_editor.text')}
            </Typography>
            <TextField
              fullWidth
              type="text"
              onChange={(event): void => setText(event.target.value)}
              value={text}
              InputProps={{
                sx: {
                  height: '48px',
                },
              }}
            />
          </Stack>
          <Stack>
            <Typography
              variant="subtitle1"
              color="text.primary"
            >
              {t('web_only:top_bar_rich_text_editor.link')}
            </Typography>
            <TextField
              fullWidth
              type="text"
              onChange={(event): void => setLink(event.target.value)}
              value={link}
              InputProps={{
                sx: {
                  height: '48px',
                },
              }}
            />
          </Stack>
        </DialogContent>
        <DialogActions sx={{ p: 0 }}>
          <Button
            onClick={onCancel}
            sx={{ mr: 1 }}
          >
            {t('general:cancel')}
          </Button>
          <Button
            onClick={onSubmit}
            variant="contained"
            disabled={!text || !link}
          >
            {t('general:accept')}
          </Button>
        </DialogActions>
      </Stack>
    </Dialog>
  );
};

export default SetLinkModal;
