import { useState } from 'react';

import { Stack } from '@mui/material';
import { IconLink } from '@tabler/icons-react';

import ActionButton from '../../components/ActionButton';
import { useTextArea } from '../../context';

import InsertLinkModal from './modal';

type InsertLinkProps = {
  title: string;
};

const InsertLink = ({ title }: InsertLinkProps) => {
  const { editor } = useTextArea();
  const [open, setOpen] = useState(false);

  if (!editor) {
    return null;
  }

  const isLinkedMedia =
    editor.isActive('resizable-media') &&
    !!editor.getAttributes('resizable-media').href;

  return (
    <Stack>
      <InsertLinkModal
        open={open}
        onClose={() => setOpen(false)}
      />
      <ActionButton
        title={title}
        icon={<IconLink />}
        onClick={() => setOpen(true)}
        isActive={editor.isActive('link') || isLinkedMedia}
        disabled={editor.isActive('code')}
      />
    </Stack>
  );
};

export default InsertLink;
