<template>
  <div class="page ctms-page-shell page--flush">

    <div class="main-content-flat unified-shell">
      <div class="filter-container unified-action-bar bar--flush">
        <el-form :inline="true" :model="filters" class="filter-form">
          <div class="filter-item-form">
            <el-input 
              v-model="filters.site_name" 
              :placeholder="TEXT.common.fields.site" 
              clearable 
              class="filter-input-comp"
            />
          </div>
          <div class="filter-item-form">
            <el-input 
              v-model="filters.keyword" 
              :placeholder="TEXT.common.fields.keyword" 
              clearable 
              class="filter-input-comp"
            />
          </div>
          <div class="filter-item-form">
            <el-button @click="resetFilters">{{ TEXT.common.actions.reset }}</el-button>
          </div>
          <div class="filter-spacer"></div>
          <el-button v-if="canCreatePrecaution" type="primary" @click="goNew">
            {{ TEXT.modules.knowledgeNotes.newTitle }}
          </el-button>
        </el-form>
      </div>
      <div class="unified-section table-section section--flush-x section--flush-top section--flush-bottom">
        <el-table
          :data="sortedItems"
          v-loading="loading"
          style="width: 100%"
          class="ctms-table"
          @row-click="onRowClick"
          :row-class-name="precautionRowClass"
          table-layout="fixed"
        >
          <el-table-column prop="site_name" :label="TEXT.common.fields.site" show-overflow-tooltip />
          <el-table-column prop="title" :label="TEXT.common.fields.title" show-overflow-tooltip />
          <el-table-column prop="level" :label="TEXT.common.fields.level" />
          <el-table-column prop="updated_at" :label="TEXT.common.labels.updatedAt" show-overflow-tooltip>
            <template #default="scope">{{ displayDateTime(scope.row.updated_at) }}</template>
          </el-table-column>
          <el-table-column v-if="canDeletePrecaution" :label="TEXT.common.labels.actions" width="120">
            <template #default="scope">
              <el-button
                v-if="canDeletePrecaution"
                link
                type="danger"
                size="small"
                :disabled="isInactiveSite(scope.row.site_name)"
                @click.stop="remove(scope.row)"
              >
                {{ TEXT.common.actions.delete }}
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <div v-if="!loading" class="table-empty">{{ TEXT.modules.knowledgeNotes.empty }}</div>
          </template>
        </el-table>
      </div>
    </div>
    <PrecautionEditorDrawer
      v-model="precautionDrawerVisible"
      @success="handlePrecautionEditorSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStudyStore } from "../../store/study";
import { listPrecautions, deletePrecaution } from "../../api/precautions";
import { fetchSites } from "../../api/sites";
import { displayDateTime } from "../../utils/display";
import { usePermission } from "../../utils/permission";
import { TEXT } from "../../locales";
import PrecautionEditorDrawer from "../knowledge/PrecautionEditorDrawer.vue";

const router = useRouter();
const study = useStudyStore();
const { can } = usePermission();
const loading = ref(false);
const precautionDrawerVisible = ref(false);
const items = ref<any[]>([]);
const sites = ref<any[]>([]);
const filters = reactive({
  site_name: "",
  keyword: "",
});

const siteActiveMap = computed(() => {
  const map: Record<string, boolean> = {};
  sites.value.forEach((site) => {
    if (site?.name) map[site.name] = !!site.is_active;
  });
  return map;
});
const isInactiveSite = (siteName?: string) => !!siteName && siteActiveMap.value[siteName] === false;
const precautionRowClass = ({ row }: { row: any }) =>
  `${row?.id ? "clickable-row" : ""}${isInactiveSite(row?.site_name) ? " row-inactive" : ""}`.trim();
const filteredItems = computed(() => {
  const siteKeyword = filters.site_name.trim().toLowerCase();
  const keyword = filters.keyword.trim().toLowerCase();
  return items.value.filter((item) => {
    if (siteKeyword && !String(item?.site_name || "").toLowerCase().includes(siteKeyword)) return false;
    if (keyword && !String(item?.title || "").toLowerCase().includes(keyword)) return false;
    return true;
  });
});
const sortedItems = computed(() =>
  [...filteredItems.value].sort((a, b) => Number(isInactiveSite(a?.site_name)) - Number(isInactiveSite(b?.site_name)))
);
const canCreatePrecaution = computed(() => can("precautions.create"));
const canDeletePrecaution = computed(() => can("precautions.delete"));

const loadSites = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  try {
    const { data } = await fetchSites(studyId, { limit: 500 });
    sites.value = Array.isArray(data) ? data : data.items || [];
  } catch {
    sites.value = [];
  }
};

const load = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  loading.value = true;
  try {
    const { data } = await listPrecautions(studyId, {}) as any;
    items.value = Array.isArray(data) ? data : data.items || [];
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => {
  filters.site_name = "";
  filters.keyword = "";
};

const goNew = () => {
  precautionDrawerVisible.value = true;
};
const goDetail = (id: string) => router.push(`/knowledge/precautions/${id}`);
const handlePrecautionEditorSuccess = () => {
  load();
};
const onRowClick = (row: any) => {
  if (!row?.id) return;
  goDetail(row.id);
};

const remove = async (row: any) => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  if (!canDeletePrecaution.value) {
    ElMessage.warning("权限不足");
    return;
  }
  if (isInactiveSite(row?.site_name)) {
    ElMessage.warning("中心已停用");
    return;
  }
  const ok = await ElMessageBox.confirm(TEXT.common.confirm.delete, TEXT.common.labels.tips).catch(() => null);
  if (!ok) return;
  try {
    await deletePrecaution(studyId, row.id);
    ElMessage.success(TEXT.common.messages.deleteSuccess);
    load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.deleteFailed);
  }
};

onMounted(async () => {
  await loadSites();
  load();
});
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
}

.filter-form {
  display: flex;
  width: 100%;
  gap: 8px;
  align-items: center;
}

.filter-item-form {
  margin-bottom: 0 !important;
  margin-right: 0 !important;
}

.filter-input-comp {
  width: 160px;
}

.filter-spacer {
  flex: 1;
}

:deep(.ctms-table .el-table__inner-wrapper::before) {
  display: none;
}

.table-empty {
  min-height: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8a97ab;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 0.02em;
}
</style>

<style>
.row-inactive td {
  color: var(--ctms-text-secondary);
  background-color: #fff7d6 !important;
}

.row-inactive .el-tag {
  opacity: 0.6;
}
</style>
