<template>
  <el-table :data="items" v-loading="loading" style="width: 100%" class="faq-table" @row-click="onRowClick">
    <el-table-column prop="question" :label="TEXT.common.fields.question" min-width="200">
      <template #default="scope">
        <el-link type="primary" :underline="false" class="question-link">
          {{ scope.row.question }}
        </el-link>
      </template>
    </el-table-column>
    <el-table-column prop="category_id" :label="TEXT.common.labels.category" width="140">
      <template #default="scope">
        {{ categoryMap[scope.row.category_id] || scope.row.category_id }}
      </template>
    </el-table-column>
    <el-table-column prop="is_active" :label="TEXT.common.fields.enabled" width="80">
      <template #default="scope">
        <el-tag :type="scope.row.is_active ? 'success' : 'info'">
          {{ scope.row.is_active ? TEXT.common.boolean.yes : TEXT.common.boolean.no }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="updated_at" :label="TEXT.common.labels.updatedAt" width="180">
      <template #default="scope">{{ displayDateTime(scope.row.updated_at) }}</template>
    </el-table-column>
    <el-table-column prop="status" :label="TEXT.common.fields.status" width="120">
      <template #default="scope">
        <el-tag :type="statusTagType(scope.row.status)" size="small">{{ statusLabel(scope.row.status) }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column :label="TEXT.common.labels.actions" width="180">
      <template #default="scope">
        <el-button v-if="canDelete(scope.row)" type="text" size="small" class="danger" @click="remove(scope.row)">
          {{ TEXT.common.actions.delete }}
        </el-button>
        <PermissionAction v-if="canEdit" action="faq.edit">
          <el-button
            type="text"
            size="small"
            @click="toggle(scope.row)"
            :style="{ color: scope.row.is_active ? '#f56c6c' : '#67c23a' }"
          >
            {{ scope.row.is_active ? TEXT.common.actions.disable : TEXT.common.actions.enable }}
          </el-button>
        </PermissionAction>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { computed } from "vue";
import { useRouter } from "vue-router";
import { deleteFaqItem, updateFaqItem } from "../api/faqs";
import type { FaqItem, FaqCategory } from "../api/faqs";
import PermissionAction from "./PermissionAction.vue";
import { displayDateTime, displayEnum } from "../utils/display";
import { useAuthStore } from "../store/auth";
import { TEXT } from "../locales";

const props = defineProps<{
  items: FaqItem[];
  categories: FaqCategory[];
  loading: boolean;
  canEdit: boolean;
}>();
const emit = defineEmits(["refresh"]);

const router = useRouter();
const auth = useAuthStore();

const categoryMap = computed(() =>
  props.categories.reduce<Record<string, string>>((acc, cur) => {
    acc[cur.id] = cur.name;
    return acc;
  }, {})
);

const view = (row: FaqItem) => {
  router.push(`/knowledge/medical-consult/${row.id}`);
};

const onRowClick = (row: FaqItem, column: any, event: MouseEvent) => {
  if (column?.property !== "question") return;
  view(row);
};

const statusLabel = (status?: string) => {
  return displayEnum(TEXT.enums.faqStatus, status || "");
};

const statusTagType = (status?: string) => {
  if (status === "RESOLVED") return "success";
  if (status === "PROCESSING") return "warning";
  return "info";
};

const canDelete = (row: FaqItem) => props.canEdit || row.created_by === auth.user?.id;


const toggle = async (row: FaqItem) => {
  const target = !row.is_active;
  const ok = await ElMessageBox.confirm(
    TEXT.modules.knowledgeMedicalConsult.confirmToggleItem.replace("{action}", target ? TEXT.common.actions.enable : TEXT.common.actions.disable),
    TEXT.common.labels.tips
  ).catch(() => null);
  if (!ok) return;
  try {
    await updateFaqItem(row.id, { is_active: target });
    ElMessage.success(TEXT.common.messages.updateSuccess);
    emit("refresh");
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.actionFailed);
  }
};

const remove = async (row: FaqItem) => {
  const ok = await ElMessageBox.confirm(
    TEXT.modules.knowledgeMedicalConsult.confirmDeleteItem.replace("{name}", row.question),
    TEXT.common.labels.tips
  ).catch(() => null);
  if (!ok) return;
  try {
    await deleteFaqItem(row.id);
    ElMessage.success(TEXT.common.messages.deleteSuccess);
    emit("refresh");
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.deleteFailed);
  }
};
</script>

<style scoped>
.faq-table :deep(.el-table__inner-wrapper::before) {
  display: none;
}

.danger {
  color: #f56c6c;
}
.question-link {
  cursor: pointer;
}
</style>
