<template>
  <div
    class="modal fade"
    id="editBlogCat"
    tabindex="-1"
    role="dialog"
    aria-labelledby="exampleModalLabel"
    aria-hidden="true"
  >
    <div class="modal-dialog modal-sm" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">ویرایش کردن دسته</h5>
          <button
            type="button"
            class="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="editCat">
            <BRow class="g-3">
              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">عنوان دسته</label>
                  <input
                    v-model="localTitle"
                    @input="clearError('localTitle')"
                    type="text"
                    class="form-control"
                    placeholder="عنوان دسته"
                    :class="{ 'is-invalid': errors.localTitle }"
                  />
                  <small v-if="errors.localTitle" class="text-danger">
                    {{ errors.localTitle }}
                  </small>
                </div>
              </BCol>

              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">انتخاب آیکن</label>
                  <b-dropdown
                    variant="outline-primary"
                    class="w-100"
                    @change="clearError('icon')"
                  >
                    <b-dropdown-item
                      v-for="(icon, index) in iconData"
                      :key="index"
                      :value="icon.component"
                      class="icon-item"
                      @click="setSelectedIcon(icon.component)"
                    >
                      <div class="icon-container">
                        <i :class="`ph-duotone ${icon.component}`"></i>
                      </div>
                    </b-dropdown-item>
                  </b-dropdown>

                  <div v-if="localIcon" class="mt-2">
                    <label class="form-label">آیکن انتخاب شده:</label>
                    <div class="selected-icon-container">
                      <i :class="`ph-duotone ${localIcon}`"></i>
                    </div>
                  </div>

                  <div v-if="!localIcon" class="mt-2">
                    <label class="form-label">آیکن انتخاب شده:</label>
                    <div class="selected-icon-container">
                      <i :class="`ph-duotone ${localIcon}`"></i>
                    </div>
                  </div>

                  <small v-if="errors.icon" class="text-danger">
                    {{ errors.icon }}
                  </small>
                </div>
              </BCol>
            </BRow>

            <!-- Submit Buttons -->
            <div
              class="d-flex justify-content-end gap-2"
              style="margin-top: 20px"
            >
              <button
                type="button"
                class="btn btn-secondary"
                data-bs-dismiss="modal"
                id="closeEditBlogCat"
              >
                بستن
              </button>
              <button type="submit" class="btn btn-primary" :disabled="loading">
                <span
                  v-if="loading"
                  class="spinner-border spinner-border-sm"
                  role="status"
                  aria-hidden="true"
                ></span>
                ذخیره
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { iconData } from "../../../views/live-preview/icon/data";
import { ref, toRef, watch } from "vue";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";

export default {
  props: {
    icon: {
      type: String,
      Required: true,
    },
    title: {
      type: String,
      Required: true,
    },
    id: {
      type: String,
      Required: true,
    },
  },
  setup(props, { emit }) {
    const localTitle = toRef(props.title);
    const localIcon = ref(props.icon);
    const localId = toRef(props.id);
    const errors = ref({});
    const loading = ref(false);

    watch(
      () => props.title,
      (newVal) => (localTitle.value = newVal)
    );

    watch(
      () => props.icon,
      (newVal) => (localIcon.value = newVal)
    );

    watch(
      () => props.id,
      (newVal) => (localId.value = newVal)
    );

    const clearError = (field) => {
      errors.value[field] = "";
    };

    const validateForm = () => {
      errors.value = {};
      if (!localTitle.value)
        errors.value.localTitle = "وارد کردن عنوان ضروری می باشد";
      if (!localIcon.value) errors.value.icon = "انتخاب آیکن ضروری است";
      return Object.keys(errors.value).length === 0;
    };

    const setSelectedIcon = (icon) => {
      localIcon.value = icon;
    };

    const editCat = () => {
      if (!validateForm()) return;
      loading.value = true;

      const formData = new FormData();
      formData.append("title", localTitle.value);
      formData.append("icon", localIcon.value);
      ApiServiece.put(`admin/blog-categories/${localId.value}`, formData)
        .then(() => {
          toast.success("!دسته با موفقیت ویرایش شد", {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .then(() => {
          setTimeout(() => {
            document.getElementById("closeEditBlogCat").click();
            emit("cat-updated");
          }, 500);
        })
        .catch((error) => {
          console.error(error);
          toast.error("!ویرایش دسته با مشکل مواجه شد", {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .finally(() => {
          loading.value = false;
        });
    };

    return {
      errors,
      loading,
      clearError,
      editCat,
      localTitle,
      iconData,
      setSelectedIcon,
      localIcon,
      localId,
    };
  },
};
</script>

<style scoped>
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 1.5rem;
}

.modal-body {
  padding: 1rem 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.input-group {
  margin-top: 0.5rem;
}

.modal-header {
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 1rem;
}

.Image-Preview {
  min-width: 100px;
  max-height: 100px;
  max-width: 100px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #ddd;
}

.selected-icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}

.selected-icon-container i {
  font-size: 2.5rem;
}

.icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 8px;
}

.icon-container i {
  font-size: 2rem;
  margin-right: 10px;
}

.icon-item {
  display: inline-block;
  width: 33%;
  padding: 5px;
  text-align: center;
}
</style>
