<template>
  <Layout>
    <BRow>
      <BCol sm="12">
        <BCard no-body>
          <BCardHeader>
            <h5>ایجاد بلاگ</h5>
          </BCardHeader>
          <BCardBody>
            <BRow class="g-3">
              <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="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>
                  <select
                    :class="{ 'is-invalid': errors.blogCat }"
                    v-model="blogCat"
                    class="form-control"
                    @change="clearError('blogCat')"
                    placeholder="انتخاب دسته بلاگ"
                  >
                    <option v-for="cat in cats" :key="cat.id" :value="cat.id">
                      {{ cat.title }}
                    </option>
                  </select>
                </div>
                <small v-if="errors.blogCat" class="text-danger">
                  {{ errors.blogCat }}
                </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>
            </BRow>
          </BCardBody>
          <BCardFooter>
            <div class="d-flex justify-content-center">
              <button
                type="submit"
                class="btn btn-primary"
                @click.prevent="submitForm"
                :disabled="loading"
              >
                <span v-if="loading">
                  <i class="fa fa-spinner fa-spin"></i> بارگذاری...
                </span>
                <span v-else>ایجاد</span>
              </button>
            </div>
          </BCardFooter>
        </BCard>
      </BCol>
    </BRow>
  </Layout>
</template>

<script>
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import { ref, onMounted, nextTick } from "vue";
import Layout from "@/layout/custom.vue";
import Quill from "quill";
import "quill/dist/quill.snow.css";

export default {
  name: "SAMPLE-PAGE",
  components: {
    Layout,
  },
  setup() {
    const loading = 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 cats = ref([]);
    const editorContent = ref("");

    const getCats = () => {
      ApiServiece.get(`admin/blog-categories`)
        .then((resp) => {
          cats.value = resp.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    };

    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 (!blogCat.value)
        errors.value.blogCat = "انتخاب دسته برای بلاگ ضروری می باشد";
      if (!author.value)
        errors.value.author = "وارد کردن نویسنده بلاگ ضروری می باشد";
      if (!editorContent.value)
        errors.value.editorContent = "وارد کردن محتوای بلاگ ضروری می باشد";
      if (!image.value) errors.value.image = "وارد کردن عکس بلاگ ضروری می باشد";
      return Object.keys(errors.value).length === 0;
    };

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

    onMounted(() => {
      getCats();
      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" }],
          ],
        },
      });

      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;
      });
    });

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

      loading.value = true;

      const formData = new FormData();
      formData.append("title", title.value);
      formData.append("slug", slug.value);
      formData.append("summary", summary.value);
      formData.append("content", editorContent.value);
      formData.append("image", image.value);
      formData.append("author", author.value);
      formData.append("blog_category_id", blogCat.value);

      ApiServiece.post(`admin/blogs`, formData, {
        headers: {
          "content-type": "multipart",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
        .then((resp) => {
          console.log(resp);
          toast.success("!بلاگ با موفقیت اضافه شد", {
            position: "top-right",
            autoClose: 1000,
          });
        })

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

    return {
      title,
      slug,
      summary,
      editor,
      cats,
      errors,
      image,
      imagePreview,
      handleImageChange,
      removeImage,
      submitForm,
      clearError,
      editorContent,
      author,
      blogCat,
      loading,
    };
  },
};
</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>
