<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" class="filter-form">
          <div class="filter-item-form">
            <el-input v-model="filters.keyword" :placeholder="TEXT.common.fields.keyword" clearable class="filter-input-comp">
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="filter-item-form">
            <el-select v-model="filters.siteId" :placeholder="TEXT.common.fields.site" clearable filterable class="filter-select-comp">
              <template #prefix>
                <el-icon><Location /></el-icon>
              </template>
              <el-option :label="TEXT.common.labels.all" value="" />
              <el-option v-for="site in siteOptions" :key="site.id" :label="site.name" :value="site.id" />
            </el-select>
          </div>
          <div class="filter-item-form">
            <el-select v-model="filters.status" :placeholder="TEXT.common.fields.status" clearable class="filter-select-comp">
              <template #prefix>
                <el-icon><CircleCheck /></el-icon>
              </template>
              <el-option :label="TEXT.common.labels.all" value="" />
              <el-option v-for="option in aeStatusOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </div>
          <div class="filter-item-form">
            <el-select v-model="filters.seriousness" :placeholder="TEXT.common.fields.seriousness" clearable class="filter-select-comp">
              <template #prefix>
                <el-icon><Warning /></el-icon>
              </template>
              <el-option :label="TEXT.common.labels.all" value="" />
              <el-option v-for="option in aeSeriousnessOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </div>
          <div class="filter-item-form">
            <el-select v-model="filters.aeType" :placeholder="TEXT.common.fields.aeType" clearable class="filter-select-comp">
              <template #prefix>
                <el-icon><Warning /></el-icon>
              </template>
              <el-option :label="TEXT.common.labels.all" value="" />
              <el-option v-for="option in aeTypeOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </div>
          <div class="filter-actions-comp">
            <el-button @click="resetFilters">{{ TEXT.common.actions.reset }}</el-button>
          </div>
        </el-form>
      </div>
      <div class="unified-section table-section section--flush-x section--flush-top section--flush-bottom">
        <el-table :data="filteredItems" v-loading="loading" style="width: 100%" class="risk-table" table-layout="fixed">
          <el-table-column prop="onset_date" :label="TEXT.common.fields.occurDate">
            <template #default="scope">{{ displayDate(scope.row.onset_date) }}</template>
          </el-table-column>
          <el-table-column prop="subject_no" :label="TEXT.modules.riskIssueSae.subjectNo" show-overflow-tooltip>
            <template #default="scope">{{ subjectMap[scope.row.subject_id] || TEXT.common.fallback }}</template>
          </el-table-column>
          <el-table-column :label="TEXT.common.fields.site" show-overflow-tooltip>
            <template #default="scope">{{ siteMap[scope.row.site_id] || TEXT.common.fallback }}</template>
          </el-table-column>
          <el-table-column prop="term" :label="TEXT.common.fields.title" show-overflow-tooltip />
          <el-table-column prop="seriousness" :label="TEXT.common.fields.seriousness">
            <template #default="scope">{{ displayEnum(TEXT.enums.aeSeriousness, scope.row.seriousness) }}</template>
          </el-table-column>
          <el-table-column prop="status" :label="TEXT.common.fields.status">
            <template #default="scope">{{ displayEnum(TEXT.enums.aeStatus, scope.row.status) }}</template>
          </el-table-column>
          <el-table-column prop="updated_at" :label="TEXT.common.labels.updatedAt" show-overflow-tooltip>
            <template #default="scope">{{ displayDate(scope.row.updated_at) }}</template>
          </el-table-column>
          <el-table-column :label="TEXT.common.labels.actions" width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" :disabled="!scope.row.subject_id" @click="goSubject(scope.row.subject_id, 'ae')">
                {{ TEXT.modules.riskIssueSae.toSubject }}
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <div v-if="!loading" class="risk-table-empty">{{ TEXT.modules.riskIssueSae.emptyDescription }}</div>
          </template>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { CircleCheck, Location, Search, Warning } from "@element-plus/icons-vue";
import { useStudyStore } from "../../store/study";
import { fetchRiskIssueAes } from "../../api/aes";
import { fetchSubjects } from "../../api/subjects";
import { fetchSites } from "../../api/sites";
import { displayDate, displayEnum } from "../../utils/display";
import { TEXT } from "../../locales";

const router = useRouter();
const study = useStudyStore();
const loading = ref(false);
const items = ref<any[]>([]);
const siteOptions = ref<Array<{ id: string; name: string }>>([]);
const siteMap = ref<Record<string, string>>({});
const subjectMap = ref<Record<string, string>>({});
const subjectSiteMap = ref<Record<string, string>>({});
const filters = ref({
  keyword: "",
  siteId: study.currentSite?.id || "",
  status: "",
  seriousness: "",
  aeType: "",
});

const aeStatusOptions = Object.entries(TEXT.enums.aeStatus).map(([value, label]) => ({ value, label }));
const aeSeriousnessOptions = Object.entries(TEXT.enums.aeSeriousness).map(([value, label]) => ({ value, label }));
const aeTypeOptions = [
  { value: "ae", label: TEXT.modules.subjectDetail.aeType.ae },
  { value: "sae", label: TEXT.modules.subjectDetail.aeType.sae },
  { value: "susar", label: TEXT.modules.subjectDetail.aeType.susar },
];

const resetFilters = () => {
  filters.value.keyword = "";
  filters.value.siteId = "";
  filters.value.status = "";
  filters.value.seriousness = "";
  filters.value.aeType = "";
};

const loadSites = async (studyId: string) => {
  try {
    const { data } = await fetchSites(studyId, { limit: 500 });
    const list = Array.isArray(data) ? data : data.items || [];
    siteOptions.value = list.map((site: any) => ({ id: site.id, name: site.name }));
    siteMap.value = list.reduce((acc: Record<string, string>, site: any) => {
      acc[site.id] = site.name;
      return acc;
    }, {});
  } catch {
    siteOptions.value = [];
    siteMap.value = {};
  }
};

const loadSubjects = async (studyId: string) => {
  const { data } = await fetchSubjects(studyId);
  const list = Array.isArray(data) ? data : data.items || [];
  subjectMap.value = list.reduce((acc: Record<string, string>, item: any) => {
    acc[item.id] = item.subject_no;
    return acc;
  }, {});
  subjectSiteMap.value = list.reduce((acc: Record<string, string>, item: any) => {
    acc[item.id] = item.site_id;
    return acc;
  }, {});
};

const load = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  loading.value = true;
  try {
    await Promise.all([loadSites(studyId), loadSubjects(studyId)]);
    const { data } = await fetchRiskIssueAes(studyId);
    items.value = (Array.isArray(data) ? data : data.items || []).sort((a: any, b: any) =>
      String(b.updated_at || "").localeCompare(String(a.updated_at || ""))
    );
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  } finally {
    loading.value = false;
  }
};

const filteredItems = computed(() => {
  const keyword = filters.value.keyword.trim().toLowerCase();
  return items.value.filter((item) => {
    const subjectId = item?.subject_id ? String(item.subject_id) : "";
    const siteId = item?.site_id || subjectSiteMap.value[subjectId] || "";
    const subjectNo = String(subjectMap.value[subjectId] || "").toLowerCase();
    const term = String(item?.term || "").toLowerCase();
    if (keyword && !subjectNo.includes(keyword) && !term.includes(keyword)) return false;
    if (filters.value.siteId && String(siteId) !== filters.value.siteId) return false;
    if (filters.value.status && item?.status !== filters.value.status) return false;
    if (filters.value.seriousness && item?.seriousness !== filters.value.seriousness) return false;
    if (filters.value.aeType && getAeType(item) !== filters.value.aeType) return false;
    return true;
  });
});

const getAeType = (item: any) => {
  if (item?.is_susar) return "susar";
  if (item?.is_sae) return "sae";
  return "ae";
};

const goSubject = (subjectId: string, tab: "ae" | "pd") => {
  if (!subjectId) return;
  router.push({ path: `/subjects/${subjectId}`, query: { tab } });
};

watch(
  () => study.currentSite,
  (newSite) => {
    filters.value.siteId = newSite?.id || "";
  }
);

onMounted(load);
</script>

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

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

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

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

.filter-select-comp {
  width: 170px;
}

.filter-actions-comp {
  margin-bottom: 0;
  margin-right: 0;
}

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

.risk-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>
