import { useRef, useState } from 'react';

import { Button, useTheme } from '@mui/material';
import { IconVariablePlus } from '@tabler/icons-react';

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

import InsertVariableMenu from './menu';
import { type InsertVariableProps } from './types';

const InsertVariable = ({ title, variables }: InsertVariableProps) => {
  const { editor } = useTextArea();
  const theme = useTheme();
  const anchorRef = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);

  if (!editor) return null;

  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  const handleSelect = (token: string, label: string) => {
    handleClose();
    editor
      .chain()
      .focus()
      .insertContent({
        type: 'variablePill',
        attrs: { token, label },
      })
      .run();
  };

  return (
    <>
      <Button
        ref={anchorRef}
        variant="outlined"
        size="small"
        startIcon={<IconVariablePlus size={16} />}
        onClick={handleOpen}
        sx={{
          textTransform: 'none',
          borderColor: theme.palette.new.border.neutral.brand,
          color: theme.palette.new.text.neutral.brand,
          typography: 'caption',
          fontWeight: 'fontWeightSemiBold',
          px: 1.5,
          py: 0.5,
          borderRadius: theme.shape.borderRadiusM,
          whiteSpace: 'nowrap',
          '&:hover': {
            borderColor: theme.palette.new.border.neutral.brand,
            backgroundColor: theme.palette.new.action.background.brand.default,
          },
        }}
      >
        {title}
      </Button>
      <InsertVariableMenu
        anchorRef={anchorRef}
        open={open}
        onClose={handleClose}
        onSelect={handleSelect}
        variables={variables}
      />
    </>
  );
};

export default InsertVariable;
