<template>
  <div
      class="modal fade"
      id="addAttribute"
      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="addAttribute">
            <BRow class="g-3">
              <!-- Brand Title -->
              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">نام رنگ</label>

                  <input
                      v-model="colorName"
                      @input="clearError('colorName')"
                      type="text"
                      class="form-control"
                      placeholder="نام رنگ"
                      :class="{ 'is-invalid': errors.colorName }"
                  />
                  <small v-if="errors.colorName" class="text-danger">
                    {{ errors.colorName }}
                  </small>
                </div>
              </BCol>

              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">انتخاب رنگ</label>
                  <div class="color-picker-wrapper">
                    <input
                        v-model="colorCode"
                        @input="clearError('colorCode')"
                        type="color"
                        class="form-control color-picker"
                        :class="{ 'is-invalid': errors.colorCode }"
                    />
                    <span
                        v-if="colorCode"
                        class="color-display"
                        :style="{ backgroundColor: colorCode }"
                    ></span>
                  </div>
                  <span> {{ colorCode }}</span>

                  <small v-if="errors.colorCode" class="text-danger">
                    {{ errors.colorCode }}
                  </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="close"
              >
                بستن
              </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 { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";

export default {
  props: {
    attributeValues: {
      type: Array,
      Required: true,
    },
  },
  setup(props, { emit }) {
    const colorName = ref();
    const colorCode = ref();
    const localAttributeValues = toRef(props.attributeValues);
    const errors = ref({});
    const loading = ref(false);

    watch(
        () => props.attributeValues,
        (newVal) => (localAttributeValues.value = newVal)
    );

    const validateForm = () => {
      errors.value = {};
      if (!colorName.value)
        errors.value.colorName = "وارد کردن نام رنگ ضروری می باشد";
      if (!colorCode.value) errors.value.colorCode = "انتخاب رنگ ضروری می باشد";

      return Object.keys(errors.value).length === 0;
    };

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

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

      loading.value = true;

      const formData = new FormData();

      formData.append("title", colorName.value);

      formData.append("code", colorCode.value);

      formData.append("attribute_id", 1);

      ApiServiece.post(`admin/attribute-values`, formData)
          .then(() => {
            toast.success("!ویژگی با موفقیت اضافه شد", {
              position: "top-right",
              autoClose: 1000,
            });
          })
          .then(() => {
            setTimeout(() => {
              //document.getElementById("close").click();
              emit("attribute-updated");
              colorName.value = "";
              colorCode.value = "";
            }, 500);
          })
          .catch((error) => {
            toast.error(`${error.response.data.message}`, {
              position: "top-right",
              autoClose: 1000,
            });
          })
          .finally(() => {
            loading.value = false;
          });
    };

    return {
      errors,
      loading,
      clearError,
      addAttribute,
      colorName,
      colorCode,
    };
  },
};
</script>

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

.modal-content {
  padding: 20px;
}

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

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

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

.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 1.5rem;
}

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

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

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

.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;
}
.color-picker-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.color-picker {
  width: 300px;
  height: 45px;
  padding: 0;
  border-radius: 10px;
  border: none;
  cursor: pointer;
}

.color-display {
  width: 30px;
  height: 30px;
  margin-left: 10px;
  border-radius: 50%;
  border: 2px solid #ccc;
  display: inline-block;
}
</style>
