<template>
  <div class="w-full">
    <div
      v-for="(form, index) in formBuilder.formFields"
      :key="'field'+index"
      class="w-12"
    >
      <span class="p-text-secondary block mb-5">{{ form.title }}</span>
      <div class="grid">
        <div class="col-6 flex" v-for="(row, indez) in form.fields" :key="indez">
          <label :for="row.field" class="font-semibold w-12rem md:mb-0">{{
            row.label
          }}</label>
          <div class="w-full">
            <component
              :is="row.component"
              v-bind="row.attributes"
              v-model="formData[row.field]"
              :key="row.field"
            ></component>
            <small v-if="errors[row.field]" class="text-red-700"
              ><i>{{ errors[row.field][0] }}</i></small
            >
          </div>
        </div>
      </div>
    </div>
    <div class="flex justify-content-end gap-2">
      <Button
        type="button"
        label="Cancel"
        severity="secondary"
        @click="close"
      ></Button>
      <Button
        type="button"
        @click="submit"
        :loading="saving"
        label="Save"
      ></Button>
    </div>
    <Toast />
  </div>
</template>
<script setup>
import { computed, onMounted, ref } from "vue";
import { useToast } from "primevue/usetoast";
import { AppService } from "@/service/security-management/AppService.js";

const appService = new AppService();
const toast = useToast();
const loading = ref(true);
const saving = ref(false);
const errors = ref({});
const props = defineProps({
  data: Object,
});
const initForm = {
  id: "",
  name: "",
  base_url:"",
  description: "",
};

const formData = ref({
  ...initForm,
});
const initData = ref({
  ...initForm,
});

const emit = defineEmits(["closeForm"]);
const close = () => {
  emit("closeForm");
};

const formBuilder = computed(() => {
  return {
    header: formData?.id ? "Update Permission" : "New Permission",
    formFields: [
      {
        title: "",
        fields: [
          {
            label: "Name",
            field: "name",
            component: "InputText",
            attributes: {
              type: "text",
              class: "w-full",
            },
          },
          {
            label: "Code",
            field: "code",
            component: "InputText",
            attributes: {
              type: "text",
              class: "w-full",
            },
          },
          {
            label: "Url",
            field: "base_url",
            component: "Textarea",
            attributes: {
              type: "text",
              class: "w-full",
            },
          },
        ],
      },
    ],
  };
});

onMounted(() => {
  if (props.data) {
    formData.value = props.data;
    initData.value = JSON.parse(JSON.stringify(formData.value));
  }
});

const submit = () => {
  console.log(JSON.stringify(initData.value), JSON.stringify(formData.value));
  if (JSON.stringify(initData.value) !== JSON.stringify(formData.value)) {
    saving.value = true;
    if (formData.value?.id) {
      appService
        .update(formData.value.id, formData.value)
        .then((res) => {
          let data = res.data;
          toast.add({
            severity: "success",
            summary: "Success",
            detail: data.message,
            life: 3000,
          });
          emit("closeForm");
        })
        .catch((errors) => {
          errors.value = errors.data;
        })
        .finally(() => {
          saving.value = false;
        });
    } else {
      appService
        .create(formData.value)
        .then((res) => {
          let data = res.data;
          emit("closeForm");
          toast.add({
            severity: "success",
            summary: "Success",
            detail: data.message,
            life: 3000,
          });
        })
        .catch((res) => {
          let data = res.response?.data;
          errors.value = data.errors;
          toast.add({
            severity: "error",
            summary: "Errors",
            detail: data.message,
            life: 3000,
          });
        })
        .finally((res) => {
          saving.value = false;
        });
    }
  } else {
    toast.add({
      severity: "warn",
      summary: "Warning",
      detail: "No data changes",
      life: 3000,
    });
  }
};
defineExpose({
  close,
});
</script>