import React, { useCallback, useRef } from 'react';
import { Box, Button } from '@wix/design-system';
import { TagSmall } from '@wix/wix-ui-icons-common';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { useWixPatternsContainer } from '../..';
import { BulkAssignTagsPopover } from '../Tags/BulkAssignTagsPopover';
import { DisabledTooltip } from '../DisabledTooltip';
import { observer } from 'mobx-react-lite';

const _TagsAssignButton = () => {
  const toolbarCollectionState = useToolbarCollectionContext();
  const { translate: t } = useWixPatternsContainer();
  const buttonRef = useRef<HTMLButtonElement | null>(null);

  const { tagsBulkAssignPopoverState } =
    toolbarCollectionState.tagsCollectionState ?? {};

  const setButtonRef = useCallback(
    (element: HTMLElement | null) => {
      if (!element || !tagsBulkAssignPopoverState) {
        return;
      }
      const el = element.querySelector('button') as HTMLButtonElement | null;
      if (!el) {
        return;
      }
      buttonRef.current = el;
      tagsBulkAssignPopoverState.triggerButtonRef = buttonRef;
    },
    [tagsBulkAssignPopoverState],
  );

  if (!tagsBulkAssignPopoverState) {
    return null;
  }

  const { tagsBulkAssignButtonState } = tagsBulkAssignPopoverState;

  return (
    <BulkAssignTagsPopover
      state={tagsBulkAssignPopoverState}
      popoverElement={
        <Box>
          <div ref={setButtonRef} style={{ display: 'contents' }}>
            <DisabledTooltip
              content={tagsBulkAssignButtonState.tooltipContent}
              disabled={!tagsBulkAssignButtonState.isDisabled}
              dataHook="tags-assign-button-disabled-tooltip"
            >
              <Button
                skin="standard"
                priority="secondary"
                size="small"
                ellipsis
                prefixIcon={<TagSmall />}
                dataHook="tags-assign-button"
                onClick={() => {
                  tagsBulkAssignPopoverState.showPopover();
                }}
                disabled={tagsBulkAssignButtonState.isDisabled}
              >
                {t('cairo.tags.collectionPage.add.CTA')}
              </Button>
            </DisabledTooltip>
          </div>
        </Box>
      }
    />
  );
};

export const TagsAssignButton = observer(_TagsAssignButton);
