<script setup>
import { useAppConfig } from "#app";
import UButton from "@nuxt/ui/components/Button.vue";
import UModal from "@nuxt/ui/components/Modal.vue";
import defu from "defu";
import { computed, reactive, toRaw, useTemplateRef } from "vue";
import AutoFormPrimitive from "./AutoFormPrimitive.vue";
const props = defineProps({
  open: { type: Boolean, required: false, default: false },
  schema: { type: null, required: true },
  initialState: { type: Object, required: false, default: () => ({}) },
  title: { type: String, required: false },
  description: { type: String, required: false },
  config: { type: Object, required: false },
  modalProps: { type: Object, required: false, default: () => ({}) }
});
const emit = defineEmits(["submit", "update:open"]);
const defaults = {
  modal: { submitLabel: "Submit", closeLabel: "Cancel" }
};
const appConfig = computed(() => {
  return defu(
    props.config,
    useAppConfig().autoForm,
    defaults
  );
});
const state = reactive({ ...props.initialState });
const formRef = useTemplateRef("form");
const isButtonDisabled = computed(() => !props.schema.safeParse(state).success);
const open = computed({
  get: () => props.open,
  set: (value) => emit("update:open", value)
});
defineExpose({
  submit: () => formRef.value?.submit(),
  form: formRef
});
async function onSubmit(event) {
  event.preventDefault();
  emit("submit", toRaw(event.data));
}
function close() {
  open.value = false;
}
</script>

<template>
  <UModal
    v-model:open="open"
    :title="title"
    :description="description"
    :ui="{ footer: 'justify-end' }"
    v-bind="modalProps"
  >
    <template #body>
      <AutoFormPrimitive
        ref="form"
        :schema="schema"
        :state="state"
        :config="config"
        @submit="onSubmit"
      >
        <template v-for="(_, name) in $slots" #[name]="slotData">
          <slot :name="name" v-bind="slotData" />
        </template>
      </AutoFormPrimitive>
    </template>

    <template #footer>
      <slot name="footer" :disabled="isButtonDisabled" :submit="() => formRef?.form?.submit()" :close="close">
        <UButton
          :label="appConfig.modal?.closeLabel"
          color="neutral"
          variant="outline"
          @click="close"
        />
        <UButton
          :label="appConfig.modal?.submitLabel"
          :disabled="isButtonDisabled"
          @click="formRef?.form?.submit()"
        />
      </slot>
    </template>
  </UModal>
</template>
