<template>
  <el-drawer
    v-if="modelValue"
    :model-value="modelValue"
    direction="rtl"
    size="620px"
    :close-on-click-modal="true"
    :show-close="false"
    class="faq-item-editor-drawer"
    @update:model-value="emit('update:modelValue', $event)"
    @close="close"
  >
    <template #header>
      <div class="editor-header">
        <div class="editor-title">{{ isEdit ? TEXT.modules.knowledgeMedicalConsult.editItem : TEXT.modules.knowledgeMedicalConsult.newItem }}</div>
      </div>
    </template>

    <el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="faq-item-form">
      <div class="form-group">
        <div class="form-group-title">
          <span class="group-dot group-dot-basic"></span>
          {{ TEXT.common.labels.basicInfo }}
        </div>
        <el-form-item :label="TEXT.common.labels.category" prop="category_id">
          <el-select v-model="form.category_id" :placeholder="TEXT.common.placeholders.select" class="full-width">
            <el-option v-for="c in categories" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="TEXT.common.fields.question" prop="question">
          <el-input v-model="form.question" />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="close">{{ TEXT.common.actions.cancel }}</el-button>
        <el-button type="primary" :loading="submitting" @click="onSubmit">{{ TEXT.common.actions.submit }}</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { createFaqItem, updateFaqItem } from "../api/faqs";
import { useStudyStore } from "../store/study";
import { TEXT, requiredMessage } from "../locales";

const props = defineProps<{ modelValue: boolean; item?: any; categories: any[] }>();
const emit = defineEmits(["update:modelValue", "success"]);

const study = useStudyStore();
const formRef = ref<FormInstance>();
const submitting = ref(false);

const form = reactive({
  study_id: "",
  category_id: "",
  question: "",
});

const rules: FormRules = {
  category_id: [{ required: true, message: requiredMessage(TEXT.common.labels.category), trigger: "change" }],
  question: [{ required: true, message: requiredMessage(TEXT.common.fields.question), trigger: "blur" }],
};

const isEdit = computed(() => !!props.item);

const reset = () => {
  form.study_id = study.currentStudy?.id || "";
  form.category_id = "";
  form.question = "";
};

watch(
  () => props.item,
  (val) => {
    if (val) {
      form.study_id = val.study_id || "";
      form.category_id = val.category_id;
      form.question = val.question;
    } else {
      reset();
    }
  },
  { immediate: true }
);

const close = () => emit("update:modelValue", false);

const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();
  submitting.value = true;
  try {
    const payload: Record<string, any> = {
      study_id: study.currentStudy?.id || null,
      category_id: form.category_id,
      question: form.question,
    };
    if (isEdit.value && props.item) {
      await updateFaqItem(props.item.id, payload);
    } else {
      await createFaqItem(payload);
    }
    ElMessage.success(TEXT.common.messages.saveSuccess);
    emit("success");
    close();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.saveFailed);
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped>
.editor-header {
  display: flex;
  align-items: center;
}

.editor-title {
  color: var(--ctms-text-main);
  font-size: 18px;
  font-weight: 700;
}

.faq-item-form {
  padding: 0 4px;
}

.form-group {
  padding: 16px 0;
}

.form-group-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  color: var(--ctms-text-main);
  font-size: 15px;
  font-weight: 700;
}

.group-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.group-dot-basic {
  background: var(--ctms-primary);
}

.full-width {
  width: 100%;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
