import { createComponent, spread, insert, effect, className, style, template, addEventListener, memo, delegateEvents } from 'solid-js/web';
import { createContext, createSignal, createMemo, Show, useContext, mergeProps, onMount, onCleanup } from 'solid-js';
import { OriginComponent, extendsEvent, atom, useEventController, emitEvent } from '@cn-ui/use';
import { Icon } from '@cn-ui/core';

const CollapseContext = createContext();

const _tmpl$$1 = /*#__PURE__*/template(`<div></div>`, 2);
const Collapse = OriginComponent(props => {
  const [controllers, CommitController] = createSignal({}, {
    equals: false
  });
  return createComponent(CollapseContext.Provider, {
    get value() {
      return {
        CommitController,
        lazyload: props.lazyload,
        destroyOnHide: props.destroyOnHide,
        onToggle: (key, state, e) => {
          const c = controllers();

          if (props.accordion && state) {
            Object.entries(c).forEach(([name, toggle]) => {
              toggle(key === name);
            });
          } else {
            c[key](state);
          }

          props.onPanelChange && props.onPanelChange(key, e);
        }
      };
    },

    get children() {
      const _el$ = _tmpl$$1.cloneNode(true);

      const _ref$ = props.ref;
      typeof _ref$ === "function" ? _ref$(_el$) : props.ref = _el$;

      spread(_el$, () => extendsEvent(props), false, true);

      insert(_el$, () => props.children);

      effect(_p$ => {
        const _v$ = props.class('cn-collapse w-full'),
              _v$2 = props.style;

        _v$ !== _p$._v$ && className(_el$, _p$._v$ = _v$);
        _p$._v$2 = style(_el$, _v$2, _p$._v$2);
        return _p$;
      }, {
        _v$: undefined,
        _v$2: undefined
      });

      return _el$;
    }

  });
});

/** 取消组件的第一次渲染 */

const CancelFirstRender = P => {
  let firstTime = true;
  const render = createMemo(() => {
    // console.log(firstTime);
    if (!firstTime) return true;
    if (P.trigger()) return true; // 如果true，那么必然会渲染
    // 隐藏的时候，判断第一次，如果为第一次则删除

    if (firstTime) {
      firstTime = false; // console.log('阻止第一次渲染');

      return false;
    }
  });
  return createComponent(Show, {
    get when() {
      return render();
    },

    get children() {
      return P.children;
    }

  });
};

const _tmpl$ = /*#__PURE__*/template(`<div><nav class="cn-collapse-summary cursor-pointer select-none px-4 py-3 leading-none active:backdrop-brightness-90 "></nav><main class="cn-collapse-container "></main></div>`, 6);
const CollapseItem = OriginComponent(props => {
  const ctx = useContext(CollapseContext);
  props = mergeProps({}, props);
  const isExpanded = props.value ?? atom(false); // 移交 Expanded 的控制权

  onMount(() => {
    ctx.CommitController(val => ({ ...val,
      [props.name]: isExpanded // 强制注入

    }));
  });
  onCleanup(() => {
    ctx.CommitController(val => {
      delete val[props.name];
      return val;
    });
  });

  const Content = () => {
    return createComponent(Show, {
      get when() {
        return !ctx.destroyOnHide || isExpanded();
      },

      get children() {
        return props.children;
      }

    });
  };

  const control = useEventController({});
  return (() => {
    const _el$ = _tmpl$.cloneNode(true),
          _el$2 = _el$.firstChild,
          _el$3 = _el$2.nextSibling;

    const _ref$ = props.ref;
    typeof _ref$ === "function" ? _ref$(_el$) : props.ref = _el$;

    spread(_el$, () => extendsEvent(props), false, true);

    addEventListener(_el$2, "click", control([e => {
      const state = !isExpanded(); // isExpanded(state);

      ctx.onToggle(props.name, state, e);
    }, emitEvent(props.onTrigger, ([e]) => [props.name, isExpanded(), e])]), true);

    insert(_el$2, () => props.header, null);

    insert(_el$2, createComponent(Icon, {
      "class": "float-right scale-125 text-slate-400",

      get name() {
        return isExpanded() ? 'keyboard_arrow_up' : 'keyboard_arrow_down';
      }

    }), null);

    insert(_el$3, (() => {
      const _c$ = memo(() => !!ctx.lazyload, true);

      return () => _c$() ? createComponent(CancelFirstRender, {
        trigger: isExpanded,

        get children() {
          return createComponent(Content, {});
        }

      }) : createComponent(Content, {});
    })());

    effect(_p$ => {
      const _v$ = props.class('cn-collapse-item box-border flex h-full flex-col overflow-hidden'),
            _v$2 = props.style,
            _v$3 = !!props.disabled,
            _v$4 = isExpanded(),
            _v$5 = !!isExpanded(),
            _v$6 = !isExpanded(),
            _v$7 = props.contentStyle;

      _v$ !== _p$._v$ && className(_el$, _p$._v$ = _v$);
      _p$._v$2 = style(_el$, _v$2, _p$._v$2);
      _v$3 !== _p$._v$3 && _el$.classList.toggle("disabled", _p$._v$3 = _v$3);
      _v$4 !== _p$._v$4 && (_el$2.open = _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && _el$3.classList.toggle("show", _p$._v$5 = _v$5);
      _v$6 !== _p$._v$6 && _el$3.classList.toggle("hide", _p$._v$6 = _v$6);
      _p$._v$7 = style(_el$3, _v$7, _p$._v$7);
      return _p$;
    }, {
      _v$: undefined,
      _v$2: undefined,
      _v$3: undefined,
      _v$4: undefined,
      _v$5: undefined,
      _v$6: undefined,
      _v$7: undefined
    });

    return _el$;
  })();
});

delegateEvents(["click"]);

export { Collapse, CollapseItem };
