<script setup lang="ts">
import Modal from "ChillMainAssets/vuejs/_components/Modal.vue";
import Create from "ChillMainAssets/vuejs/OnTheFly/components/Create.vue";
import { CreateComponentConfig } from "ChillMainAssets/types";
import { trans, SAVE } from "translator";
import { useTemplateRef } from "vue";
import { Person } from "ChillPersonAssets/types";
import { Thirdparty } from "../../../../../../ChillThirdPartyBundle/Resources/public/types";

const emit = defineEmits<{
  (e: "onPersonCreated", payload: { person: Person }): void;
  (e: "onThirdPartyCreated", payload: { thirdParty: Thirdparty }): void;
  (e: "close"): void;
}>();

const props = defineProps<CreateComponentConfig & { modalTitle: string }>();
const modalDialogClass = { "modal-xl": true, "modal-scrollable": true };

type CreateComponentType = InstanceType<typeof Create>;

const create = useTemplateRef<CreateComponentType>("create");

const onPersonCreated = ({ person }: { person: Person }): void => {
  emit("onPersonCreated", { person });
};

const onThirdPartyCreated = ({
  thirdParty,
}: {
  thirdParty: Thirdparty;
}): void => {
  emit("onThirdPartyCreated", { thirdParty: thirdParty });
};

function save(): void {
  console.log("save from CreateModal");
  create.value?.save();
}

defineExpose({ save });
</script>

<template>
  <teleport to="body">
    <modal
      @close="() => emit('close')"
      :modal-dialog-class="modalDialogClass"
      :hide-footer="false"
    >
      <template #header>
        <h3 class="modal-title">{{ modalTitle }}</h3>
      </template>
      <template #body-head>
        <div class="modal-body">
          <Create
            ref="create"
            :allowedTypes="props.allowedTypes"
            :action="props.action"
            :query="props.query"
            :parent="props.parent"
            @onPersonCreated="onPersonCreated"
            @onThirdPartyCreated="onThirdPartyCreated"
          ></Create>
        </div>
      </template>
      <template #footer>
        <button class="btn btn-save" type="button" @click.prevent="save">
          {{ trans(SAVE) }}
        </button>
      </template>
    </modal>
  </teleport>
</template>

<style scoped lang="scss"></style>
