import { Button } from '@wix/design-system';
import React, { useEffect } from 'react';
import { CustomFieldsWidgetState } from '../../state';
import { CustomFieldOrigin, withoutDefaults } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { CustomFieldsPanelEntry } from './CustomFieldsPanelEntry';
import { cairoFiltersPanelUsed } from '@wix/bex-core/bi';
import { SettingsSmall } from '@wix/wix-ui-icons-common';
import { CustomFieldsDisabledTooltip } from '../CustomFields';

export interface ManageFieldsCTAButtonProps {
  origin: CustomFieldOrigin;
  state: CustomFieldsWidgetState;
}

export function _ManageFieldsCTAButton({
  origin,
  state,
}: ManageFieldsCTAButtonProps) {
  const {
    container: { translate: t },
  } = state;

  useEffect(() => {
    state.panels.registerSidePanel('customFields', CustomFieldsPanelEntry);
  }, []);

  return (
    <CustomFieldsDisabledTooltip
      disabled={!state.dataExtension.hasWritePermissions}
      content={t('cairo.customFields.writePermission.tooltip')}
    >
      <Button
        priority="secondary"
        dataHook="manage-fields-button"
        size="small"
        prefixIcon={<SettingsSmall />}
        onClick={() => {
          const isOpened = state.panels.toggleSidePanel('customFields');
          state.reportBi(
            withoutDefaults(cairoFiltersPanelUsed)({
              isOpened,
              feature: 'Manage custom fields',
              origin,
            }),
          );
        }}
      >
        {t('cairo.customFields.manageFields.CTA')}
      </Button>
    </CustomFieldsDisabledTooltip>
  );
}

export const ManageFieldsCTAButton = observer(_ManageFieldsCTAButton);
