import { children, mergeProps, onMount, createMemo, onCleanup } from 'solid-js';
import { OriginComponent, atomization } from '@cn-ui/use';
import tippy from 'tippy.js';
import 'tippy.js/dist/tippy.css';
import 'tippy.js/animations/scale.css';

const defaultProps = {
  animation: 'scale'
};
/**
 * @zh Popup 层控制组件
 * @link https://atomiks.github.io/tippyjs/v6/tippy-instance/
 */

const Trigger = OriginComponent(props => {
  const child = children(() => props.children);
  const disabled = atomization(props.disabled ?? false);
  const visible = atomization(props.visible ?? false);
  const p = mergeProps(defaultProps, props, {
    onShow(instance) {
      visible(true);
      props.onShow && props.onShow(instance);
    },

    onHide(instance) {
      visible(false);
      props.onHide && props.onHide(instance);
    }

  });
  onMount(() => {
    const instance = tippy(child.toArray()[0], p);
    createMemo(() => {
      disabled() ? instance.disable() : instance.enable();
    }, [disabled]);
    createMemo(() => {
      if (visible() !== instance.state.isVisible) {
        instance.state.isVisible ? instance.hide() : instance.show();
        visible(instance.state.isVisible);
      }
    }, [visible]);
    onCleanup(() => {
      instance && instance.destroy();
    });
  });
  return child();
});

export { Trigger };
