<script setup>
import { useDialogPluginComponent } from "quasar";
import { ref } from "vue";
const props = defineProps({
  title: {
    type: String,
    default: null
  },
  width: {
    type: String,
    default: "500px"
  },
  save: {
    type: Function,
    default: null
  },
  cancel: {
    type: Function,
    default: null
  },
  value: {
    type: Object,
    default: () => {
      return {};
    }
  },
  showNotification: {
    type: Boolean,
    default: true
  }
});
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
import { useQuasar } from "quasar";
const $q = useQuasar();
const loading = ref(false);
const emits = defineEmits(["submit"]);
const onSubmit = async (data, node) => {
  emits("submit", data);
  if (props.save) {
    loading.value = true;
    try {
      await props.save(data);
      if (props.showNotification) {
        $q.notify({
          type: "positive",
          message: "Data saved successfully"
        });
      }
      onDialogOK(data);
    } catch (error) {
      $q.dialog({
        title: "Error",
        message: error.message
      });
    } finally {
      loading.value = false;
    }
  } else {
    onDialogOK(data);
  }
};
const onCancel = async () => {
  if (props.cancel) {
    await props.cancel();
  }
  onDialogCancel();
};
</script>

<template>
    <q-dialog ref="dialogRef">

        <q-card :style="{ width }" :loading="loading" class="q-dialog-plugin">
            <q-toolbar>
                <q-toolbar-title v-if="title">
                    {{ title }}
                </q-toolbar-title>
                <q-space />
                <q-btn icon="sym_o_close" flat round dense v-close-popup />
            </q-toolbar>

            <form-kit type="form" :bordered="false" :actions="false" :value="value" #default="context"
                @submit="onSubmit">

                <q-card-section>
                    <slot name="default" v-bind="context"></slot>
                </q-card-section>
                <q-card-actions align="right">
                    <q-btn icon="sym_o_close" :label="$t('Cancel')" @click="onCancel" unelevated />
                    <q-btn icon="sym_o_check" :label="$t('Save')" type="submit" color="primary" unelevated
                        :disabled="!context.state.valid" />
                </q-card-actions>
            </form-kit>

            <q-inner-loading :showing="loading"></q-inner-loading>
        </q-card>
    </q-dialog>
</template>
