<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" v-for="(row, indez) in form.fields" :key="indez">
        <div class="col-3 pt-4">
          <label :for="row.field" class="font-semibold w-8rem md:mb-0"
            >{{ row.label
            }}<span v-if="row.required" class="text-red-600">*</span></label
          >
        </div>
        <div class="col-9">
          <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 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, reactive, ref } from "vue";
import { useToast } from "primevue/usetoast";
import { UserService } from "@/service/security-management/UserService.js";
import axios from "axios";

const userService = new UserService();
const toast = useToast();
const loading = ref(true);
const saving = ref(false);
const errors = ref({});
const props = defineProps({
  data: Object,
});
const initForm = {
  id: "",
  name: "",
  email: "",
  password: "",
  role_id: [],
};
const selections = reactive({
  roles: [],
});
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",
            required: true,
            attributes: {
              type: "text",
              class: "w-full",
            },
          },
          {
            label: "Email",
            field: "email",
            component: "InputText",
            required: true,
            attributes: {
              type: "email",
              class: "w-full",
            },
          },
          {
            label: "Password",
            field: "password",
            component: "InputText",
            required: true,
            attributes: {
              type: "password",
              class: "w-full",
            },
          },
          // {
          //   label: "Roles",
          //   field: "role_id",
          //   component: "MultiSelect",
          //   required: true,
          //   attributes: {
          //     options: selections.roles,
          //     class: "w-full",
          //     placeholder: "Select roles",
          //     optionLabel: "name",
          //     optionValue: "code",
          //     display: "chip",
          //   },
          // },
        ],
      },
    ],
  };
});
const getSelection = () => {
  return userService.getSelection().then((res) => {
    let data = res.data;
    selections.roles = data.roles;
  });
};
onMounted(async () => {
  await getSelection();
  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) {
      userService
        .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 {
      userService
        .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>