import * as React from 'react';
import * as CheckControlBase from '@tesseract-design/web-base-checkcontrol';

export type ToggleSwitchProps = Omit<React.HTMLProps<HTMLInputElement>, 'size' | 'type' | 'style'> & {
  /**
   * Should the component occupy the whole width of its parent?
   */
  block?: boolean,
  /**
   * Does the component need to conserve space?
   */
  compact?: boolean,
  /**
   * Complementary content of the component.
   */
  subtext?: React.ReactNode,
}

/**
 * Component for performing an action upon activation (e.g. when clicked).
 *
 * This component functions as a regular button.
 */
export const ToggleSwitch = React.forwardRef<HTMLInputElement, ToggleSwitchProps>(
  (
    {
      children,
      block = false,
      compact = false,
      subtext,
      className: _className,
      as: _as,
      ...etcProps
    }: ToggleSwitchProps,
    ref,
  ) => {
    const styleProps = React.useMemo<CheckControlBase.CheckControlBaseArgs>(() => ({
      block,
      compact,
      menuItem: false,
      appearance: CheckControlBase.CheckControlAppearance.SWITCH,
      type: 'checkbox',
    }), [block, compact]);

    return (
      <div
        className={CheckControlBase.ClickAreaWrapper(styleProps)}
      >
        <label
          className={CheckControlBase.ClickArea()}
        >
          <input
            {...etcProps}
            type="checkbox"
            ref={ref}
            className={CheckControlBase.CheckStateContainer(styleProps)}
          />
          <span>
            <span />
            <span
              className={CheckControlBase.CheckIndicatorArea(styleProps)}
            >
              <span
                className={CheckControlBase.CheckIndicatorWrapper(styleProps)}
              >
                <svg
                  className={CheckControlBase.CheckIndicator(styleProps)}
                  viewBox="0 0 24 24"
                  role="presentation"
                >
                  <polyline
                    points="20 6 9 17 4 12"
                  />
                </svg>
                <svg
                  className={CheckControlBase.CheckIndicator(styleProps)}
                  viewBox="0 0 24 24"
                  role="presentation"
                >
                  <polyline
                    points="20 12 4 12"
                  />
                </svg>
              </span>
            </span>
            <span>
              {children}
              {
                subtext
                && (
                  <>
                    <br />
                    <span
                      className={CheckControlBase.Subtext()}
                      data-testid="subtext"
                    >
                      {subtext}
                    </span>
                  </>
                )
              }
            </span>
          </span>
        </label>
      </div>
    );
  },
);

ToggleSwitch.displayName = 'ActionButton';
