import React, { Fragment, useState, useEffect } from 'react';
import { IconButton, Icons, Separator } from '@storybook/components';
import { ForwardIcon, NextIcon } from './Icons';
import { stringify } from 'qs';
import { styled } from '@storybook/theming';
import { isDefined } from '../../../types';
import { getTestPath, useForceUpdate } from '../../shared/helpers';
const Button = styled(IconButton)({
  '&:disabled': {
    opacity: 0.5,
    cursor: 'default'
  },
  '&:disabled:hover': {
    color: 'inherit'
  }
});
export const Tools = _ref => {
  let {
    manager
  } = _ref;
  const [buttonClicked, setButtonClicked] = useState();
  const [isRunning, setRunning] = useState(manager.status.isRunning);
  const forceUpdate = useForceUpdate();
  const test = manager.getCurrentTest();
  useEffect(() => {
    const unsubscribe = manager.onChangeTest(() => {
      forceUpdate();
    });
    return unsubscribe;
  }, [manager, forceUpdate]);
  useEffect(() => {
    const unsubscribe = manager.onUpdateStatus(_ref2 => {
      let {
        isRunning
      } = _ref2;
      if (isDefined(isRunning)) setRunning(isRunning);
    });
    return unsubscribe;
  }, [manager]);
  if (!test) return null;
  function renderButton(type, title, onClick, icon) {
    const handleClick = () => {
      setButtonClicked(type);
      onClick();
    };
    const disabled = isRunning && buttonClicked != null && buttonClicked !== type;
    return (
      /*#__PURE__*/
      // @ts-expect-error Fixed in https://github.com/storybookjs/storybook/pull/26623
      React.createElement(Button, {
        onClick: () => {
          isRunning ? manager.onStop() : handleClick();
        },
        title: disabled ? '' : title,
        disabled: disabled
      }, buttonClicked === type && isRunning ? /*#__PURE__*/React.createElement(Icons, {
        icon: 'stop'
      }) : icon)
    );
  }
  return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(IconButton, {
    href: `http://localhost:${__CREEVEY_CLIENT_PORT__ || __CREEVEY_SERVER_PORT__ || 3000}/?${stringify({
      testPath: getTestPath(test)
    })}`,
    target: "_blank",
    title: "Show in Creevey UI"
  }, /*#__PURE__*/React.createElement(Icons, {
    icon: "sharealt"
  })), /*#__PURE__*/React.createElement(Separator, null), renderButton('RunAll', 'Run all', manager.onStartAllTests, /*#__PURE__*/React.createElement(ForwardIcon, null)), renderButton('RunStoryTests', 'Run all story tests', manager.onStartAllStoryTests, /*#__PURE__*/React.createElement(NextIcon, {
    width: 15,
    height: 11
  })), renderButton('RunTest', 'Run', manager.onStart, /*#__PURE__*/React.createElement(Icons, {
    icon: "play"
  })));
};