import { deprecate, error } from '@vizality/util/logger';
import { toKebabCase } from '@vizality/util/string';
import { joinClassNames } from '@vizality/util/dom';
import { getCaller } from '@vizality/util/file';
import React, { memo } from 'react';

import { Icon, AsyncComponent } from '..';

const SwitchItem = AsyncComponent.fromDisplayName('SwitchItem');

const labels = [ 'Component', 'Settings', 'SwitchItem' ];
const _deprecate = (...message) => deprecate({ labels, message });
const _error = (...message) => error({ labels, message });

/**
 *
 * @component
 * @param {object} props
 * @param {boolean} props.value
 * @param {string} props.description
 * @param {Function} props.onChange
 * @param {string|React.Component} props.children
 * @param {boolean} [props.disabled]
 * @param {boolean} [props.separator]
 * @param {boolean} [props.requiresRestart=false] Whether the app requires a restart for the change to take effect
 * @param {string} [props.warning]
 * @param {string} [props.danger]
 * @param {string} [props.help]
 * @param {string} [props.switchTooltip]
 * @param {string} [props.className]
 * @param {string} [props.id]
 * @returns {React.MemoExoticComponent<function(): React.ReactElement>}
 */
export default memo(({ separator = true, description, requiresRestart, info, switchTooltip, onChange, children, className, id, ...other }) => {
  /**
   * @deprecated
   */
  if (other.note) {
    _deprecate('"note" property has been deprecated. Please use "description" instead.');
  }

  /**
   * Handles requires restart prop. If the prop is true, we'll tie in the confirmation
   * restart modal with the onChange prop.
   * @returns {Promise<void>}
   */
  const handleRequiresRestart = async () => {
    try {
      await onChange?.();
      vizality.api.actions.invokeAction('CONFIRM_RESTART');
    } catch (err) {
      return _error(err);
    }
  };

  return (
    <SwitchItem
      hideBorder={Boolean(!separator)}
      onChange={requiresRestart ? handleRequiresRestart : onChange}
      className={joinClassNames('vz-settings-item', 'vz-settings-switch-item', className)}
      tooltipNote={switchTooltip}
      note={description || other.note} // props.note is only here for legacy reasons
      {...other}
    >
      <div
        className='vz-settings-switch-item-inner'
        id={id || `setting-switch-${toKebabCase(getCaller()?.id)}-${children.toString()}`}
      >
        {children}
        {info && (
          <Icon
            name='help-circle'
            size='16px'
            tooltip={info}
            className='vz-settings-item-info-badge'
          />
        )}
        {requiresRestart && (
          <Icon
            name='refresh'
            size='16px'
            tooltip='Requires Restart'
            className='vz-settings-item-restart-badge'
          />
        )}
      </div>
    </SwitchItem>
  );
});


