<template>
  <Layout>
    <BRow>
      <BCol sm="12">
        <BCard no-body>
          <BCardHeader>
            <h5>ایجاد بلاگ</h5>
          </BCardHeader>
          <BCardBody>
              <Steppy
                  v-model:step="step"
                  :tabs="[
                    { title: 'انتخاب دسته بندی', isValid: true },
                    { title: 'ترجمه ها', isValid: true },
                  ]"
                  backText="قبلی"
                  nextText="بعدی"
                  doneText="ذخیره"
                  primaryColor1="#04A9F5"
                  circleSize="45"
                  :finalize="submitForm"
              >
                <template #1>
                  <BRow class="g-3">
                    <BCol md="6">
                      <div class="form-group">
                        <label class="form-label">تصویر بلاگ</label>

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

                        <div v-if="imagePreview" class="mt-2">
                          <img
                              :src="imagePreview"
                              alt="Image Preview"
                              class="img-fluid rounded shadow-sm Image-Preview"
                          />
                          <button
                              type="button"
                              @click="removeImage()"
                              class="delete-btn"
                          >
                            <i class="fa fa-trash f-16"></i>
                          </button>
                        </div>

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

                    <BCol md="6">
                      <div class="form-group">
                        <label class="form-label">دسته</label>
                        <VueSelect
                            :isLoading="categorySelectorLoader"
                            v-model="blogCat"
                            :options="formattedCategories"
                            placeholder="دسته ای را انتخاب کنید"
                            @search="handleSearch"
                            @change="clearError('blogCat')"
                            style="--vs-min-height: 48px; --vs-border-radius: 8px"
                        />
                      </div>
                      <small v-if="errors.blogCat" class="text-danger">
                        {{ errors.blogCat }}
                      </small>
                    </BCol>

                    <button
                        :disabled="loadingStep"
                        @click="handlerAddCategory"
                        class="btn rounded btn-primary w-auto"
                    >
                      <span
                          v-if="loadingStep"
                          class="spinner-border spinner-border-sm"
                          role="status"
                      />
                      ذخیره
                    </button>
                  </BRow>
                </template>

                <template #2>
                  <form @submit.prevent="submitForm" class="mt-4">
                    <BRow class="g-3">
                      <BCol>
                        <div class="form-group">
                          <label class="form-label">انتخاب زبان</label>
                          <select
                              v-model="locale"
                              class="form-control"
                              placeholder="انتخاب کنید"
                          >
                            <option
                                key="fa"
                                value="fa"
                            >
                              فارسی
                            </option>
                            <option
                                key="en"
                                value="en"
                            >
                              انگلیسی
                            </option>
                            <option
                                key="ar"
                                value="ar"
                            >
                              عربی
                            </option>
                          </select>
                        </div>
                      </BCol>

                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">عنوان بلاگ</label>
                          <input
                              type="text"
                              v-model="title"
                              class="form-control"
                              placeholder="عنوان بلاگ"
                              :class="{ 'is-invalid': errors.title }"
                              @input="clearError('title')"
                          />
                        </div>
                        <small v-if="errors.title" class="text-danger">
                          {{ errors.title }}
                        </small>
                      </BCol>

                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">کلمه کلیدی</label>
                          <input
                              type="text"
                              v-model="slug"
                              class="form-control"
                              placeholder="کلمه کلیدی بلاگ"
                              :class="{ 'is-invalid': errors.slug }"
                              @input="clearError('slug')"
                          />
                        </div>
                        <small v-if="errors.slug" class="text-danger">
                          {{ errors.slug }}
                        </small>
                      </BCol>

                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">خلاصه</label>
                          <textarea
                              v-model="summary"
                              class="form-control"
                              placeholder="خلاصه ای از بلاگ"
                              :class="{ 'is-invalid': errors.summary }"
                              @input="clearError('summary')"
                          />
                        </div>
                        <small v-if="errors.summary" class="text-danger">
                          {{ errors.summary }}
                        </small>
                      </BCol>

                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">نویسنده</label>
                          <input
                              type="text"
                              v-model="author"
                              class="form-control"
                              placeholder="نویسنده"
                              :class="{ 'is-invalid': errors.author }"
                              @input="clearError('author')"
                          />
                        </div>
                        <small v-if="errors.author" class="text-danger">
                          {{ errors.author }}
                        </small>
                      </BCol>

                      <BCol md="12">
                        <div class="form-group">
                          <label class="form-label">محتوا</label>
                          <div
                              @input="clearError('editorContent')"
                              ref="editor"
                              class="quill-editor"
                          ></div>
                        </div>
                        <small v-if="errors.editorContent" class="text-danger">
                          {{ errors.editorContent }}
                        </small>
                      </BCol>
                      <!-- Submit Buttons -->
                      <div
                          class="d-flex justify-content-between gap-2"
                          style="margin-top: 20px"
                      >
<!--                        <button-->
<!--                            class="btn btn-secondary"-->
<!--                            @click="step&#45;&#45;"-->
<!--                        >-->
<!--                          قبلی-->
<!--                        </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>
                    </BRow>
                  </form>
                </template>
              </Steppy>
          </BCardBody>
        </BCard>
      </BCol>
    </BRow>
  </Layout>
</template>

<script>
import VueSelect from "vue3-select-component";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import { ref, nextTick , computed } from "vue";
import Layout from "@/layout/custom.vue";
import Quill from "quill";
import "quill/dist/quill.snow.css";
import {Steppy} from "vue3-steppy";
import {BRow} from "bootstrap-vue-next";

export default {
  name: "SAMPLE-PAGE",
  components: {
    BRow,
    Steppy,
    Layout,
    VueSelect,
  },
  setup() {
    const loading = ref(false);
    const loadingStep = ref(false);
    const image = ref();
    const imagePreview = ref();
    const errors = ref({});
    const title = ref("");
    const slug = ref("");
    const summary = ref("");
    const blogCat = ref();
    const author = ref("");
    const editor = ref(null);
    const categories = ref([]);
    const editorContent = ref("");
    const categorySelectorLoader = ref(false)
    const step = ref(1)
    const blogCategoryId = ref(null)
    const locale = ref('fa')
    const quillInstance = ref()

    const handleSearch = async (searchTerm) => {
      if (searchTerm.length < 3) return;
      categorySelectorLoader.value = true;
      try {
        const response = await ApiServiece.get(
          `admin/blog-categories?title=${searchTerm}`
        );
        categories.value = response.data.data;
        categorySelectorLoader.value = false;
      } catch (error) {
        categorySelectorLoader.value = false;
        categories.value = [];
      }
    };

    const formattedCategories = computed(() =>
      Array.isArray(categories.value)
        ? categories.value.map((category) => ({
            value: category?.translation?.id,
            label: category?.translation?.title,
          }))
        : []
    );

    const removeImage = () => {
      image.value = null;
      imagePreview.value = null;

      const fileInput = document.querySelector('input[type="file"]');
      if (fileInput) {
        fileInput.value = "";
      }
    };

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

      if (file) {
        errors.value.image = null;

        image.value = file;

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

    const validateForm = () => {
      errors.value = {};
      if (!title.value) errors.value.title = "وارد کردن عنوان بلاگ الزامی است";
      if (!slug.value)
        errors.value.slug = "وارد کردن کلمه کلیدی بلاگ ضروری می باشد";
      if (!summary.value)
        errors.value.summary = "وارد کردن خلاصه بلاگ ضروری می باشد";
      if (!author.value)
        errors.value.author = "وارد کردن نویسنده بلاگ ضروری می باشد";
      if (!editorContent.value)
        errors.value.editorContent = "وارد کردن محتوای بلاگ ضروری می باشد";
      return Object.keys(errors.value).length === 0;
    };

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

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

      loading.value = true;

      const params = {
        title: title.value,
        slug: slug.value,
        summary: summary.value,
        content: editorContent.value,
        author: author.value,
        locale: locale.value,
      }

      ApiServiece.post(`admin/blogs/${blogCategoryId.value}/translations`, params, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
        .then(({ data }) => {
          toast.success(data?.message, {
            position: "top-right",
            autoClose: 1000,
          });

          title.value = ""

          slug.value = ""

          summary.value = ""

          quillInstance.value.root.innerHTML = ""

          author.value = ""

          locale.value = "fa"
        })

        .catch(() => {
          toast.error("!مشکلی در اضافه کردن بلاگ پیش آمد", {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .finally(() => {
          loading.value = false;
        });
    };

    const handlerAddCategory = async () => {
      try {
        loadingStep.value = true;

        const formData = new FormData();

        formData.append("image", image.value);

        formData.append("blog_category_id", blogCat.value);

        const { data: { message, success, data } } = await ApiServiece.post(`admin/blogs`, formData, {
          headers: {
            "content-type": "multipart",
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        })

        if (success) {
          toast.success(message)

          initQuill()

          blogCategoryId.value = data?.id

          step.value++
        }
      } catch (e) {
        toast.error(e?.response?.data?.message)
      } finally {
        loadingStep.value = false;
      }
    }

    const initQuill = () => {
      nextTick(() => {
        if (!editor.value) {
          console.error("Editor container not found!");
          return;
        }

        const quill = new Quill(editor.value, {
          theme: "snow",
          modules: {
            toolbar: [
              [{ header: "1" }, { header: "2" }, { font: [] }],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ align: [] }],
              ["bold", "italic", "underline"],
              ["link", "image"],
              [{ script: "sub" }, { script: "super" }],
              [{ direction: "rtl" }],
            ],
          },
        });

        quillInstance.value = quill

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

        quill.format("direction", "rtl");

        nextTick(() => {
          const rtlButton = quill.container.querySelector(".ql-direction[data-value='rtl']");

          if (rtlButton) {
            rtlButton.click();
          }
        });

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

    return {
      title,
      slug,
      summary,
      editor,
      categories,
      errors,
      image,
      imagePreview,
      handleImageChange,
      removeImage,
      submitForm,
      clearError,
      editorContent,
      author,
      blogCat,
      loading,
      loadingStep,
      step,
      handleSearch,
      categorySelectorLoader,
      formattedCategories,
      handlerAddCategory,
      blogCategoryId,
      locale,
      quillInstance
    };
  },
};
</script>

<style scoped>
.quill-editor {
  height: 300px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.quill-editor .ql-container {
  font-family: "Vazir", "Arial", sans-serif;
  font-size: 14px;
}

.quill-editor .ql-editor {
  padding: 10px;
  text-align: right;
}

.ql-editor {
  direction: rtl;
  text-align: right;
}

.ql-editor::before {
  content: attr(placeholder);
  direction: rtl !important;
  text-align: right;
}
.Image-Preview {
  min-width: 200px;
  max-height: 200px;
  max-width: 200px;
  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;
  margin-right: 200px;
}

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

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

.delete-btn:focus {
  outline: none;
}
</style>
