import Spinner from '@design-system/ProgressIndicators/Spinner';
import { Node, NodeViewWrapper, ReactNodeViewRenderer } from '@tiptap/react';

// Skeleton Loader Component for Image/Video Upload
const ImageLoaderComponent = ({ node }: { node: any }) => {
  const { imageLoaderId, width = 240, height = 180 } = node.attrs;

  return (
    <NodeViewWrapper
      data-type="image-loader"
      data-image-loader-id={imageLoaderId}
      as="div"
      style={{
        borderRadius: '8px',
        backgroundColor: '#e5e7eb',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        width: `${width}px`,
        height: `${height}px`,
        maxWidth: '100%',
      }}
    >
      <Spinner sx={{ width: 48, height: 48 }} />
    </NodeViewWrapper>
  );
};

// Skeleton Loader Extension
const ImageLoader = Node.create({
  name: 'image-loader',
  group: 'block',
  atom: true,
  draggable: false,
  selectable: true,

  addAttributes() {
    return {
      imageLoaderId: { default: null },
      width: { default: 240 },
      height: { default: 180 },
    };
  },

  parseHTML() {
    return [
      {
        tag: 'div[data-type="image-loader"]',
        getAttrs: (dom: HTMLElement) => {
          return {
            imageLoaderId: dom.getAttribute('data-image-loader-id'),
            width: parseInt(dom.style.width) || 240,
            height: parseInt(dom.style.height) || 180,
          };
        },
      },
    ];
  },

  renderHTML({ node }) {
    const { width, height } = node.attrs;
    return [
      'div',
      {
        'data-type': 'image-loader',
        'data-image-loader-id': node.attrs.imageLoaderId,
        style: `display: block; width: ${width}px; height: ${height}px;`,
      },
    ];
  },

  addNodeView() {
    return ReactNodeViewRenderer(ImageLoaderComponent, {
      as: 'div',
    });
  },
});

export default ImageLoader;
