<template>
  <div
    class="modal fade"
    id="editCat"
    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">
              <!-- Brand Title -->
              <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>

              <!-- Brand Image Upload -->
              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">تصویر برند</label>

                  <input
                    type="file"
                    @input="clearError('localImage')"
                    accept="image/*"
                    @change="handleImageChange"
                    class="form-control"
                    :class="{ 'is-invalid': errors.localImage }"
                  />

                  <div v-if="imagePreview" class="mt-2">
                    <img
                      :src="imagePreview"
                      alt="Image Preview"
                      class="img-fluid rounded shadow-sm Image-Preview"
                    />
                  </div>

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

            <BRow class="g-3">
              <!-- Brand Description -->
              <BCol lg="12">
                <div class="form-group">
                  <label class="form-label">توضیحات برند</label>
                  <textarea
                    v-model="localDesc"
                    @input="clearError('localDesc')"
                    type="text"
                    class="form-control"
                    placeholder="توضیحات برند"
                    :class="{ 'is-invalid': errors.localDesc }"
                  ></textarea>
                  <small v-if="errors.localDesc" class="text-danger">
                    {{ errors.localDesc }}
                  </small>
                </div>
              </BCol>
            </BRow>

            <BRow class="g-3">
              <!-- Brand Description -->
              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">انتخاب پدر</label>
                  <select
                    v-model="localParent"
                    class="form-control"
                    placeholder="انتخاب کنید"
                  >
                    <option
                      v-for="parent in allLocalParents"
                      :key="parent.id"
                      :value="parent.id"
                    >
                      {{ parent.title }}
                    </option>
                  </select>
                </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="closeEdit"
              >
                بستن
              </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 { ref, toRef, watch } from "vue";
import ApiServiece from "@/services/ApiService";

import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import { iconData } from "../../../views/live-preview/icon/data";

export default {
  props: {
    id: {
      type: String,
      required: true,
    },
    title: {
      type: String,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
    image: {
      type: String,
      required: true,
    },
    parent: {
      type: String,
      required: true,
    },
    allParents: {
      type: Array,
      Required: true,
    },
    icon: {
      type: String,
      Required: true,
    },
  },

  setup(props, { emit }) {
    const localIcon = toRef(props.icon);
    const imagePreview = ref(null);
    const allLocalParents = toRef(props.allParents);
    const localParent = toRef(props.parent);
    const localTitle = toRef(props.title);
    const localDesc = toRef(props.description);
    const localImage = toRef(props.image);
    const image = ref(null);
    const localId = toRef(props.id);
    const errors = ref({});

    const loading = ref(false);

    const handleImageChange = (event) => {
      const file = event.target.files[0];

      if (file) {
        if (!file.type.startsWith("image/")) {
          errors.value.image = "لطفا یک فایل تصویری انتخاب کنید";
          imagePreview.value = null;
          return;
        }

        errors.value.localImage = null;

        image.value = file;

        const reader = new FileReader();
        reader.onload = () => {
          imagePreview.value = reader.result;
        };
        reader.readAsDataURL(file);
      }
    };

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

    watch(
      () => props.title,
      (newVal) => (localTitle.value = newVal)
    );
    watch(
      () => props.description,
      (newVal) => (localDesc.value = newVal)
    );
    watch(
      () => props.image,
      (newVal) => {
        localImage.value = newVal;
        imagePreview.value = newVal;
      }
    );

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

    watch(
      () => props.parent,
      (newVal) => (localParent.value = newVal)
    );

    watch(
      () => props.allParents,
      (newVal) => (allLocalParents.value = newVal)
    );

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

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

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

    const editCat = () => {
      console.log(localId.value);
      if (!validateForm()) {
        toast.error("لطفا فیلد های لازم را وارد نمایید", {
          position: "top-right",
          autoClose: 1000,
        });
        return;
      }
      loading.value = true;

      const formData = new FormData();
      formData.append("title", localTitle.value);
      formData.append("description", localDesc.value);
      formData.append("icon", localIcon.value);

      if (image.value) {
        formData.append("image", image.value);
      }
      if (localParent.value) {
        formData.append("parent_id", localParent.value);
      }
      formData.append("_method", "put");

      ApiServiece.post(`admin/categories/${localId.value}`, formData, {
        headers: {
          "content-type": "multipart",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
        .then(() => {
          toast.success("!دسته با موفقیت ویرایش شد", {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .then(() => {
          setTimeout(() => {
            document.getElementById("closeEdit").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,
      localDesc,
      localImage,
      handleImageChange,
      imagePreview,
      iconData,
      localParent,
      allLocalParents,
      setSelectedIcon,

      localIcon,
    };
  },
};
</script>

<style scoped>
.profile-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-upload-icon {
  font-size: 64px;
  color: #6c757d;
  border: 2px dashed #6c757d;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 20px;
}

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

.modal-body {
  padding: 20px;
}

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

.input-group {
  margin-top: 0.5rem;
}
.profile-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-upload-btn {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 2px solid #007bff;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.profile-upload-btn i {
  font-size: 20px;
  color: #007bff;
}

.profile-image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

.profile-placeholder {
  border: 2px dashed #007bff;
}

.d-none {
  display: none;
}
.profile-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-upload-btn {
  width: 30px;
  height: 30px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
  background-color: #fff;
  cursor: pointer;
}

.profile-upload-btn i {
  font-size: 16px;
  color: #007bff;
}

.profile-image-preview img,
.profile-placeholder {
  width: 80px;
  height: 80px;
}

.profile-placeholder i {
  font-size: 40px;
}
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 1.5rem; /* Increased padding for better spacing */
}

.modal-header {
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 1rem; /* Added padding-bottom to separate the header from the content */
}

.modal-body {
  padding: 1rem 1.5rem; /* Adjusted padding for a more balanced layout */
}

.form-group {
  margin-bottom: 1.5rem; /* Increased margin between form groups */
}

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

.profile-image-preview:hover .overlay {
  opacity: 1;
}

.profile-image-preview:hover img,
.profile-image-preview:hover .profile-placeholder {
  opacity: 0.7;
}
.Image-Preview {
  min-width: 100px;
  max-height: 100px;
  max-width: 100px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #ddd;
}
.delete-btn {
  display: flex;
  align-items: center;
  padding: 3px;
  font-size: 10px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
  gap: 8px; /* Space between icon and text */
  margin-right: 100px;
}

.delete-btn:hover {
  background-color: #c0392b;
  transform: scale(1.05);
}

.delete-btn:active {
  background-color: #a93226;
}

.delete-btn:focus {
  outline: none;
}
.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>
