<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin overflow-hidden" style="width: 700px; max-width: 95vw">
      <DefaultDialogHeader :title="title" @close="onDialogCancel" />
      <q-form ref="formRef" @submit="onOKClick">
        <q-card-section class="row q-col-gutter-sm q-pt-none">
          <DefaultInput
            v-model="form.name"
            v-model:error="validationErrors.name"
            :rules="[inputRules.required]"
            :label="$t('common.terms.name')"
            class="col-12"
          />
          <CategorySelect
            v-model="selectedCategory"
            v-model:error="validationErrors.category_id"
            type="service"
            :label="$t('parceiro.service_category')"
            class="col-md-6 col-12"
          />
          <DefaultInput
            v-model="form.service_number"
            v-model:error="validationErrors.service_number"
            :label="$t('parceiro.service_number')"
            class="col-md-6 col-12"
          />
          <DefaultInput
            v-model="form.price"
            v-model:error="validationErrors.price"
            :label="$t('parceiro.price')"
            type="number"
            class="col-md-4 col-12"
          />
          <DefaultInput
            v-model="form.associate_price"
            v-model:error="validationErrors.associate_price"
            :label="$t('parceiro.associate_price')"
            type="number"
            class="col-md-4 col-12"
          />
          <DefaultInput
            v-model="form.supplier_price"
            v-model:error="validationErrors.supplier_price"
            :label="$t('parceiro.supplier_price')"
            type="number"
            class="col-md-4 col-12"
          />
          <DefaultInput
            v-model="form.description"
            v-model:error="validationErrors.description"
            :label="$t('common.terms.description')"
            type="textarea"
            autogrow
            class="col-12"
          />
          <div class="col-12">
            <q-toggle
              v-model="form.requires_scheduling"
              :label="$t('parceiro.requires_scheduling')"
              color="violet-normal"
            />
          </div>
        </q-card-section>
        <q-card-actions>
          <q-space />
          <q-btn
            outline
            color="negative"
            :label="$t('common.actions.cancel')"
            @click="onDialogCancel"
          />
          <q-btn
            color="violet-normal"
            :label="service ? $t('common.actions.save') : $t('common.actions.add')"
            type="submit"
            :loading="loading"
            :disable="!hasUpdatedFields"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, useTemplateRef, watch } from "vue";
import { useInputRules } from "src/composables/useInputRules";
import { useDialogPluginComponent } from "quasar";
import { useI18n } from "vue-i18n";
import { createService, updateService } from "src/api/partnerAgreementService";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import CategorySelect from "src/components/selects/CategorySelect.vue";

defineEmits([...useDialogPluginComponent.emits]);

const { service, partnerAgreementId, title } = defineProps({
  service: {
    type: Object,
    default: null,
  },
  partnerAgreementId: {
    type: Number,
    required: true,
  },
  title: {
    type: String,
    default: () => useI18n().t("common.actions.add"),
  },
});

const { inputRules } = useInputRules();
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const formRef = useTemplateRef("formRef");

const selectedCategory = ref(
  service?.category ? { label: service.category.name, value: service.category.id } : null,
);

const { form, getUpdatedFields, hasUpdatedFields } = useFormUpdateTracker({
  partner_agreement_id: partnerAgreementId,
  name:                 service?.name              ?? "",
  description:          service?.description       ?? "",
  service_number:       service?.service_number    ?? "",
  category_id:          service?.category_id       ?? null,
  price:                service?.price             ?? null,
  associate_price:      service?.associate_price   ?? null,
  supplier_price:       service?.supplier_price    ?? null,
  requires_scheduling:  service?.requires_scheduling ?? false,
});

const { loading, validationErrors, execute: submitForm } = useSubmitHandler({
  onSuccess: () => onDialogOK(true),
  formRef: formRef,
});

watch(selectedCategory, (val) => {
  form.category_id = val?.value ?? null;
});

const onOKClick = async () => {
  if (service) {
    await submitForm(() => updateService(service.id, getUpdatedFields.value));
  } else {
    await submitForm(() => createService({ ...form }));
  }
};
</script>
