import { Box } from '@mui/material';
import {
  Node,
  NodeViewWrapper,
  type ReactNodeViewProps,
  ReactNodeViewRenderer,
} from '@tiptap/react';

const VariablePillComponent = ({ node }: ReactNodeViewProps) => {
  const { label } = node.attrs;
  const dashIndex = (label as string)?.indexOf(' - ') ?? -1;
  const categoryPart = dashIndex !== -1 ? label.slice(0, dashIndex) : label;
  const fieldPart = dashIndex !== -1 ? label.slice(dashIndex + 3) : null;

  return (
    <NodeViewWrapper
      as="span"
      style={{ display: 'inline', lineHeight: 'inherit' }}
    >
      <Box
        component="span"
        contentEditable={false}
        sx={{
          display: 'inline-flex',
          alignItems: 'center',
          backgroundColor: theme => theme.palette.new.background.elements.brand,
          color: theme => theme.palette.new.text.neutral.brand,
          border: '1px solid',
          borderColor: theme => theme.palette.new.border.neutral.brand,
          borderRadius: 1,
          px: 0.75,
          py: 0.125,
          fontSize: '0.85em',
          fontFamily: 'inherit',
          lineHeight: 'inherit',
          whiteSpace: 'nowrap',
          userSelect: 'all',
        }}
      >
        <Box
          component="span"
          sx={{ fontWeight: 'fontWeightSemiBold' }}
        >
          {categoryPart}
        </Box>
        {fieldPart != null && (
          <Box
            component="span"
            sx={{ fontWeight: 'fontWeightRegular' }}
          >
            {' - '}
            {fieldPart}
          </Box>
        )}
      </Box>
    </NodeViewWrapper>
  );
};

const VariablePill = Node.create({
  name: 'variablePill',
  group: 'inline',
  inline: true,
  atom: true,
  selectable: true,
  draggable: false,

  addAttributes() {
    return {
      token: { default: null },
      label: { default: null },
    };
  },

  parseHTML() {
    return [
      {
        tag: 'span[data-variable-token]',
        getAttrs: (dom: HTMLElement) => ({
          token: dom.getAttribute('data-variable-token'),
          label:
            dom.getAttribute('data-variable-label') || dom.textContent || '',
        }),
      },
    ];
  },

  renderHTML({ node }) {
    const label: string = node.attrs.label || '';
    const attrs = {
      'data-variable-token': node.attrs.token,
      'data-variable-label': label,
      class: 'variable-pill',
    };

    const dashIndex = label.indexOf(' - ');
    if (dashIndex !== -1) {
      return [
        'span',
        attrs,
        ['span', { style: 'font-weight: 600' }, label.slice(0, dashIndex)],
        ` - ${label.slice(dashIndex + 3)}`,
      ];
    }

    return ['span', attrs, label];
  },

  addNodeView() {
    return ReactNodeViewRenderer(VariablePillComponent, {
      as: 'span',
      attrs: {
        style: 'display: inline;',
      },
    });
  },
});

export default VariablePill;
