<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-12 flex"
          v-for="(row, indez) in form.fields"
          :key="indez"
        >
          <label :for="row.field" class="font-semibold w-12rem md:mb-0"
            >{{ row.label }}
            <span v-if="row.required" class="text-red-700">*</span></label
          >
          <div class="w-full">
            <component
              :is="row.component"
              v-bind="row.attributes"
              v-model="formData[row.field]"
              :key="row.field"
              @[row.event]="row.handleEvent"
            ></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 { SlideService } from "@/service/website/SlideService.js";
import SingleImg from "@/components/form/SingleImg.vue";

const slideService = new SlideService();
const toast = useToast();
const loading = ref(true);
const saving = ref(false);
const errors = ref({});
const editorRef = ref();
const props = defineProps({
  data: Object,
});
const initForm = {
  id: "",
  name: "",
  image: "",
  description: "",
};
const preview = ref(null);

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

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

const formBuilder = computed(() => {
  return {
    header: formData?.id ? "Update Slide" : "New Slide",
    formFields: [
      {
        title: "",
        fields: [
          {
            label: "Title",
            field: "name",
            component: "InputText",
            required: true,
            attributes: {
              type: "text",
              class: "w-full",
            },
          },
          {
            label: "Image",
            field: "image",
            required: true,
            component: SingleImg,
            attributes: {
              upload: false,
              type: "file",
              accept: "image/*",
              maxFileSize: 10000000,
              showUploadButton: false,
              showCancelButton: false,
              preview: preview.value,
            },
            event: "update:modelValue",
            handleEvent: (file) => {
              preview.value = file ? URL.createObjectURL(file) : null;
            },
          },
          {
            label: "Description",
            field: "description",
            component: "Textarea",
            attributes: {
              type: "textarea",
              class: "w-full",
              rows: 4,
            },
          },
        ],
      },
    ],
  };
});
const editorLoad = ({ instance }) => {
  instance.setContents(
    instance.clipboard.convert({
      html: formData.value.description,
    })
  );
};
onMounted(() => {
  if (props.data) {
    formData.value = props.data;
    initData.value = JSON.parse(JSON.stringify(formData.value));
    preview.value = formData.value.image_url;
  }
});

const updateModel = (event) => {};
const finalData = (data) => {
  const submitData = new FormData();
  Object.keys(data).forEach((key) => {
    submitData.append(key, data[key]);
  });
  return submitData;
};
const submit = async() => {
  if (JSON.stringify(initData.value) !== JSON.stringify(formData.value)) {
    saving.value = true;
    let submitData = finalData(formData.value);
    if (formData.value?.id) {
      await handleUpdate(submitData)
    } else {
      await handleCreate(submitData)
    }
  } else {
    toast.add({
      severity: "warn",
      summary: "Warning",
      detail: "No data changes",
      life: 3000,
    });
  }
};
const handleUpdate = (submitData) => {
  slideService
    .update(formData.value.id,submitData)
    .then((res) => {
      let data = res.data;
      emit("closeForm");
      toast.add({
        severity: "success",
        summary: "Success",
        detail: data.message,
        life: 3000,
      });
    })
    .catch((err) => {
      const error = err.response.data;
      saving.value = false;
      errors.value = error.errors ?? [];
      toast.add({
        severity: "error",
        summary: "Errors",
        detail: error.message,
        life: 3000,
      });
    })
    .finally((res) => {
      
    });
};
const handleCreate = (submitData) => {
  slideService
    .create(submitData)
    .then((res) => {
      let data = res.data;
      toast.add({
        severity: "success",
        summary: "Success",
        detail: data.message,
        life: 3000,
      });
      emit("closeForm");
    })
    .catch((err) => {
      const error = err.response.data;
      saving.value = false;
      errors.value = error.errors ?? [];
      toast.add({
        severity: "error",
        summary: "Errors",
        detail: error?.message,
        life: 3000,
      });
    })
    .finally(() => {});
};
defineExpose({
  close,
});
</script>