<script setup>
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import moment from "jalali-moment";
import { ref, onMounted, nextTick } from "vue";
import Layout from "@/layout/custom.vue";
import "dropzone/dist/dropzone.css";
import Quill from "quill";
import "quill/dist/quill.snow.css";
import ApiService from "@/services/ApiService";
import DatePicker from "vue3-persian-datetime-picker";
const isFirstLoad = ref(true);

const settings = ref([]);
const editors = ref({});
const loading = ref({}); // Track loading state per setting

const getSettings = async () => {
  try {
    const response = await ApiService.get("admin/settings");
    settings.value = response.data.data;

    settings.value.forEach((setting) => {
      if (setting.type === "image" && setting.value) {
        setting.preview = setting.value;
        localStorage.setItem("logo", setting.value);
      }
      loading.value[setting.id] = false;
    });

    await nextTick();
    if (isFirstLoad.value) {
      initQuillEditors();
      isFirstLoad.value = false;
    }
  } catch (error) {
    console.error("Error fetching settings:", error);
  }
};

const initQuillEditors = () => {
  settings.value.forEach((setting) => {
    if (setting.type === "longtext" && !editors.value[setting.id]) {
      const quillContainer = document.getElementById(`editor-${setting.id}`);
      if (quillContainer) {
        const quill = new Quill(quillContainer, {
          theme: "snow",
          modules: {
            toolbar: [
              [{ header: "1" }, { header: "2" }, { font: [] }],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ align: [] }],
              ["bold", "italic", "underline"],
              ["link"], // Removed "image" from here
              [{ script: "sub" }, { script: "super" }],
              [{ direction: "rtl" }],
            ],
          },
        });

        quill.root.setAttribute("dir", "rtl");
        quill.format("direction", "rtl");

        quill.root.innerHTML = setting.value || "";
        quill.on("text-change", () => {
          setting.value = quill.root.innerHTML;
        });

        editors.value[setting.id] = quill;
      }
    }
  });
};

const previewImage = (event, setting) => {
  const file = event.target.files[0];
  if (file) {
    setting.preview = URL.createObjectURL(file);
    setting.file = file;
  }
};

const saveSetting = async (setting) => {
  loading.value[setting.id] = true;
  try {
    if (setting.type === "image" && setting.preview) {
      const formData = new FormData();
      formData.append("value", setting.file);
      formData.append("_method", "put");

      await ApiService.post(`admin/settings/${setting.id}`, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
     
    } else if (setting.type === "date" && setting.value) {
      const georgianDate = moment(
        setting.value,
        "jYYYY/jMM/jDD HH:mm:ss"
      ).format("YYYY-MM-DD HH:mm:ss");
      await ApiService.put(`admin/settings/${setting.id}`, {
        value: georgianDate,
      });
    } else {
      await ApiService.put(`admin/settings/${setting.id}`, {
        value: setting.value,
      });
    }
    getSettings()
    toast.success("!تنظیمات با موفیت ذخیره شد", {
      position: "top-right",
      autoClose: 1000,
    });
  } catch (error) {
    console.error("Error saving setting:", error);
    toast.error(`${error?.response?.data?.message}`, {
      position: "top-right",
      autoClose: 1000,
    });
  } finally {
    loading.value[setting.id] = false;
  }
};

onMounted(() => {
  getSettings();
});
</script>

<style>
.vue-dropzone {
  border: 2px dashed #dbe0e5;
}
.quill-editor {
  min-height: 150px;
}
</style>

<template>
  <Layout>
    <BRow>
      <div class="col-sm-12">
        <BCard no-body>
          <BCardHeader>
            <h5>تنظیمات سایت</h5>
          </BCardHeader>
          <BCardBody>
            <div
              v-for="setting in settings"
              :key="setting.id"
              class="mb-3 row align-items-center"
            >
              <label class="col-form-label col-sm-3 text-sm-end">
                {{ setting?.title }}
              </label>
              <div class="col-lg-6 col-sm-7">
                <template v-if="setting?.type === 'longtext'">
                  <div class="form-group">
                    <div
                      :id="'editor-' + setting?.id"
                      class="quill-editor"
                    ></div>
                  </div>
                </template>

                <template v-else-if="setting.type === 'string'">
                  <input
                    type="text"
                    v-model="setting.value"
                    class="form-control"
                  />
                </template>

                <template v-else-if="setting.type === 'number'">
                  <input
                    type="text"
                    v-model="setting.value"
                    class="form-control"
                  />
                </template>

                <template v-else-if="setting.type === 'date'">
                  <DatePicker
                    v-model="setting.value"
                    type="datetime"
                    :format="'jYYYY/jMM/jDD HH:mm:ss'"
                    class="form-control"
                  />
                </template>

                <template v-else-if="setting.type === 'image'">
                  <div class="form-group">
                    <input
                      type="file"
                      accept="image/*"
                      class="form-control"
                      @change="previewImage($event, setting)"
                    />
                    <!-- Wrap image preview in a container to control layout -->
                    <div
                      v-if="setting.preview"
                      class="mt-2 d-flex justify-content-end"
                    >
                      <img
                        :src="setting.preview"
                        alt="Preview"
                        class="img-thumbnail"
                        width="150"
                      />
                    </div>
                  </div>
                </template>
              </div>

              <!-- Button Container -->
              <div class="col-lg-3 col-sm-2 text-start">
                <button
                  class="btn btn-primary"
                  @click="saveSetting(setting)"
                  :disabled="loading[setting.id]"
                >
                  <span
                    v-if="loading[setting.id]"
                    class="spinner-border spinner-border-sm"
                  ></span>
                  <span v-else>ذخیره</span>
                </button>
              </div>
            </div>
          </BCardBody>
        </BCard>
      </div>
    </BRow>
  </Layout>
</template>
