<script>
import Layout from "@/layout/custom.vue";
import { useRoute } from "vue-router";
import { onMounted, ref } from "vue";
import ApiServiece from "@/services/ApiService";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import Swal from "sweetalert2";
export default {
  name: "SAMPLE-PAGE",
  components: {
    Layout,
  },
  setup() {
    const route = useRoute();
    const text = ref("");
    const answerText = ref();
    const faqs = ref(null);
    const status = ref("");
    const userAnswer = ref(null);
    const loading = ref();
    const isAnswerExist = ref(null);

    const getFaqs = () => {
      ApiServiece.get(`admin/faqs/${route.params.id}?children=1`).then(
        (resp) => {
          faqs.value = resp.data.data;
          console.log(faqs.value, "faqs");
          text.value = faqs.value.text;
          status.value = faqs.value.status;
          answerText.value = faqs.value?.answer?.text;
          if (faqs.value?.answer) {
            isAnswerExist.value = true;
          } else {
            isAnswerExist.value = false;
          }
        }
      );
    };

    const changeStatus = (op) => {
      let text, successMessage, errorMessage;
      if (op === "confirmed") {
        text = `آیای می خواهید این پرسش را قبول کنید؟`;
        successMessage = "!پرسش با موفقیت قبول شد";
        errorMessage = "!مشکلی در تغییر وضعیت پرسش ایجاد شد";
      } else if (op === "rejected") {
        text = `آیا می خواهید این پرسش را رد کنید؟`;
        successMessage = "!پرسش با موفقیت رد شد";
        errorMessage = "!مشکلی در تغییر وضعیت پرسش ایجاد شد";
      }

      Swal.fire({
        text: text,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "بله!",
        cancelButtonText: "خیر",
      }).then((result) => {
        if (result.isConfirmed) {
          const formData = new FormData();
          formData.append("status", op);

          ApiServiece.put(`admin/faqs/${route.params.id}`, formData)
            .then(() => {
              toast.success(successMessage, {
                position: "top-right",
                autoClose: 3000,
              });
              getFaqs();
            })
            .catch(() => {
              toast.error(errorMessage, {
                position: "top-right",
                autoClose: 3000,
              });
            });
        }
      });
    };

    const submitAnswer = () => {
      loading.value = true;
      const formData = new FormData();
      formData.append("text", answerText.value);
      if (faqs.value.answer) {
        ApiServiece.put(`admin/faqs/${faqs.value?.answer?.id}`, formData)
          .then((resp) => {
            console.log(resp, "resp");
            loading.value = false;

            toast.success(`${resp.data.message}`, {
              position: "top-right",
              autoClose: 3000,
            });
          })
          .catch(() => {
            toast.error("! خطا در ارسال پاسخ", {
              position: "top-right",
              autoClose: 3000,
            });
            loading.value = false;
          });
      } else {
        loading.value = true;
        const formData = new FormData();
        formData.append("parent_id", route.params.id);
        formData.append("text", answerText.value);
        ApiServiece.post(`admin/faqs`, formData)
          .then((resp) => {
            toast.success(`${resp.data.message}`, {
              position: "top-right",
              autoClose: 3000,
            });
            loading.value = false;
          })
          .catch(() => {
            toast.error("! خطا در ارسال پاسخ", {
              position: "top-right",
              autoClose: 3000,
            });
            loading.value = false;
          });
      }
    };

    onMounted(() => {
      getFaqs();
    });

    const getStatusBadgeClass = (status) => {
      switch (status) {
        case "answered":
          return "bg-success";
        case "pending":
          return "bg-warning";
        case "rejected":
          return "bg-danger";
        case "confirmed":
          return "bg-primary";
        default:
          return "bg-secondary";
      }
    };

    return {
      text,
      status,
      userAnswer,
      changeStatus,
      getStatusBadgeClass,
      answerText,
      submitAnswer,
      loading,
      isAnswerExist,
    };
  },
};
</script>

<template>
  <Layout>
    <BRow>
      <BCard no-body class="shadow-lg rounded-3">
        <BCardBody>
          <h3 class="mb-4 text-center text-primary font-weight-bold">
            جزییات پرسش و پاسخ
          </h3>

          <BRow class="mb-4">
            <BCol class="text-center">
              <BDropdown variant="info" text="تغییر وضعیت" class="me-2">
                <BDropdownItem @click="changeStatus('rejected')"
                  >رد شده <i class="ph-duotone ph-x-circle"></i
                ></BDropdownItem>
                <BDropdownItem @click="changeStatus('confirmed')"
                  >تایید شده <i class="ph-duotone ph-check-circle"></i>
                </BDropdownItem>
              </BDropdown>
            </BCol>
          </BRow>

          <div class="text-center mb-4">
            <span
              :class="['badge', getStatusBadgeClass(status), 'px-3', 'py-2']"
            >
              {{
                status === "answered"
                  ? "جواب داده شده"
                  : status === "pending"
                  ? "در انتظار"
                  : status === "rejected"
                  ? "رد شده"
                  : status === "confirmed"
                  ? "تایید شده"
                  : "وضعیت نامشخص"
              }}
            </span>
          </div>

          <!-- FAQ Text Display -->
          <div v-if="text" class="faq-text-container mb-4">
            <p class="faq-text">{{ text }}</p>
          </div>

          <div class="faq-answer-container mt-4">
            <label for="user-answer" class="text-muted">پاسخ شما:</label>
            <textarea
              v-model="answerText"
              id="user-answer"
              placeholder="پاسخ خود را وارد کنید..."
              rows="5"
            ></textarea>
          </div>

          <div class="d-flex justify-content-center mt-4">
            <BButton
              v-if="isAnswerExist"
              variant="primary"
              class="me-2"
              :disabled="loading"
              @click="submitAnswer(`edit`)"
            >
              <span
                v-if="loading"
                class="spinner-border spinner-border-sm"
                role="status"
                aria-hidden="true"
              ></span>
              <!-- Show loading spinner -->
              <span v-else>ویرایش پاسخ</span>
            </BButton>

            <BButton
              v-if="!isAnswerExist"
              variant="primary"
              class="me-2"
              :disabled="loading"
              @click="submitAnswer(`add`)"
            >
              <span
                v-if="loading"
                class="spinner-border spinner-border-sm"
                role="status"
                aria-hidden="true"
              ></span>
              <!-- Show loading spinner -->
              <span v-else>ارسال پاسخ</span>
            </BButton>
          </div>
        </BCardBody>
      </BCard>
    </BRow>
  </Layout>
</template>

<style scoped>
.faq-text-container {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  white-space: pre-line;
}

.faq-text {
  font-size: 1.2rem;
  color: #333;
  line-height: 1.6;
}

.faq-answer-container {
  margin-top: 20px;
}

textarea {
  width: 100%;
  min-height: 150px;
  padding: 12px;
  font-size: 1rem;
  border-radius: 5px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  background-color: #f8f9fa;
  transition: all 0.3s;
}

textarea:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 5px rgba(38, 143, 255, 0.5);
}

textarea::placeholder {
  color: #888;
}

/* Style for status badge */
.badge {
  font-size: 1rem;
  padding: 10px 20px;
  border-radius: 20px;
  color: #fff;
  text-transform: capitalize;
}

.shadow-lg {
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}

.font-weight-bold {
  font-weight: 600;
}

/* Button styling */
button {
  transition: background-color 0.3s, transform 0.3s;
}

button:hover {
  transform: scale(1.05);
}

/* Flex for button center alignment */
.d-flex {
  display: flex;
  justify-content: center;
}
</style>
