import { useState } from 'react';

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

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

import InsertImageModal, { type InsertImageModalProps } from './modal';

export type InsertImageProps = {
  title: string;
  uploaderProps?: InsertImageModalProps['uploaderProps'];
};

const InsertImage = ({ title, uploaderProps }: InsertImageProps) => {
  const { editor } = useTextArea();
  const [open, setOpen] = useState(false);

  if (!editor) return null;

  return (
    <Stack>
      {!!uploaderProps && (
        <InsertImageModal
          open={open}
          onClose={() => setOpen(false)}
          uploaderProps={uploaderProps}
        />
      )}
      <ActionButton
        title={title}
        icon={<IconPhoto />}
        onClick={() => setOpen(true)}
        isActive={isMediaActive(editor, 'img')}
        disabled={!uploaderProps || editor.isActive('code')}
      />
    </Stack>
  );
};

export default InsertImage;
