import { IButton } from "@inkline/inkline/components/IButton";
import { IInput } from "@inkline/inkline/components/IInput";
import { translate } from "@inkline/inkline/i18n";
import { uid } from "@grozav/utils";
import { computed, defineComponent, h, markRaw, ref } from "vue";
import { useModalBuilder } from "@inkline/inkline/composables/modals/builder";
import { useForm } from "@inkline/inkline/composables";
import { validate } from "@inkline/inkline/validation";
import { IForm } from "@inkline/inkline/components/IForm";
import { IFormGroup } from "@inkline/inkline/components/IFormGroup";
import { IFormError } from "@inkline/inkline/components/IFormError";
export function usePrompt() {
  const modalService = useModalBuilder();
  return (options) => new Promise((resolve, reject) => {
    const id = uid("prompt");
    const schema = ref(
      useForm(
        options.schema || {
          input: {
            validators: ["required"]
          }
        }
      )
    );
    const disabled = computed(() => schema.value.invalid || schema.value.pristine);
    modalService.show({
      id,
      type: "prompt",
      onClose: () => reject(new Error("Prompt cancelled")),
      header: options.title,
      body: options.body || h("div", [
        h("p", options.message),
        h(
          IForm,
          {
            modelValue: schema,
            "onUpdate:modelValue"(value) {
              schema.value = value;
            }
          },
          () => [
            ...options.inputs ?? [
              h(IFormGroup, {}, () => [
                h(IInput, {
                  name: "input",
                  placeholder: "Enter a value...",
                  ...options.inputProps
                }),
                h(IFormError, {
                  for: "input"
                })
              ])
            ]
          ]
        )
      ]),
      footer: options.footer || markRaw(
        defineComponent({
          setup() {
            return () => h("div", [
              h(
                IButton,
                {
                  onClick: () => {
                    modalService.hide({ id });
                    reject(new Error("Prompt cancelled"));
                  }
                },
                () => options.cancelButtonText ?? translate("modals.cancel")
              ),
              h(
                IButton,
                {
                  onClick: () => {
                    schema.value = validate(schema.value);
                    if (schema.value.valid) {
                      modalService.hide({ id });
                      resolve(schema.value);
                    }
                  },
                  disabled: disabled.value,
                  color: "primary"
                },
                () => options.confirmButtonText ?? translate("modals.confirm")
              )
            ]);
          }
        })
      ),
      ...options
    });
  });
}
