import { defineComponent, h, ref, shallowRef } from 'vue';
import { type UpdatePasswordProps, default as UpdatePasswordDialog } from './components/UpdatePassword.vue';

export function useUpdatePassword() {
  let pending: PromiseWithResolvers<boolean> | undefined;
  const updatePasswordProps = shallowRef<UpdatePasswordProps>();
  const show = ref(false);

  function settle(ok: boolean) {
    pending?.resolve(ok);
    pending = undefined;
  }

  const api = {
    open(props: UpdatePasswordProps) {
      pending?.resolve(false);
      pending = Promise.withResolvers<boolean>();
      updatePasswordProps.value = props;
      show.value = true;
      return pending.promise;
    },
    close() {
      show.value = false;
      settle(false);
    },
  };

  const Wrapper = defineComponent({
    name: 'WrapperResetPassword',
    setup(_, { attrs, slots }) {
      return () => {
        const props = updatePasswordProps.value;
        if (!props) return null;

        return h(
          UpdatePasswordDialog,
          {
            ...attrs,
            ...props,
            show: show.value,
            'onUpdate:show'(v: boolean) {
              show.value = v;
            },
            onComplete() {
              show.value = false;
              settle(true);
            },
            onCancel() {
              show.value = false;
              settle(false);
            },
          },
          slots
        );
      };
    },
  });

  return [Wrapper, api] as const;
}
