<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">
          <el-form-item 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>
          </el-form-item>
          <el-form-item 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>
          </el-form-item>
          <el-form-item 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 statusOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </el-form-item>
          <el-form-item class="filter-actions-comp">
            <el-button @click="resetFilters">{{ TEXT.common.actions.reset }}</el-button>
          </el-form-item>
        </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%" table-layout="fixed" class="risk-table">
          <el-table-column prop="pd_no" :label="TEXT.common.fields.pdNo" min-width="160" show-overflow-tooltip />
          <el-table-column prop="subject_no" :label="TEXT.modules.subjectManagement.screeningNo" min-width="160" show-overflow-tooltip />
          <el-table-column :label="TEXT.common.fields.site" min-width="160" show-overflow-tooltip>
            <template #default="scope">{{ siteMap[scope.row.site_id] || TEXT.common.fallback }}</template>
          </el-table-column>
          <el-table-column prop="status" :label="TEXT.common.fields.status" min-width="160">
            <template #default="scope">{{ displayEnum(TEXT.enums.pdStatus, scope.row.status) }}</template>
          </el-table-column>
          <el-table-column prop="description" :label="TEXT.common.fields.pdDescription" min-width="160" show-overflow-tooltip />
          <el-table-column :label="TEXT.common.labels.actions" min-width="160" align="center">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="goSubject(scope.row.subject_id)">
                {{ TEXT.common.actions.view }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <StateEmpty v-if="!loading && filteredItems.length === 0" :description="TEXT.modules.riskIssuePd.emptyDescription" />
      </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 } from "@element-plus/icons-vue";
import { useStudyStore } from "../../store/study";
import { listStudySubjectPds } from "../../api/subjectPds";
import { fetchSites } from "../../api/sites";
import { displayEnum } from "../../utils/display";
import StateEmpty from "../../components/StateEmpty.vue";
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 filters = ref({
  keyword: "",
  siteId: study.currentSite?.id || "",
  status: "",
});

const statusOptions = Object.entries(TEXT.enums.pdStatus).map(([value, label]) => ({ value, label }));

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

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 load = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  loading.value = true;
  try {
    await loadSites(studyId);
    const { data } = await listStudySubjectPds(studyId);
    const list = Array.isArray(data) ? data : data.items || [];
    const getPdSeq = (pdNo: string) => {
      const text = String(pdNo || "");
      const matched = text.match(/^PD(\d+)$/i);
      if (!matched) return Number.POSITIVE_INFINITY;
      const num = Number(matched[1]);
      return Number.isFinite(num) ? num : Number.POSITIVE_INFINITY;
    };
    items.value = list.sort((a: any, b: any) => getPdSeq(a?.pd_no) - getPdSeq(b?.pd_no));
  } 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 pdNo = String(item?.pd_no || "").toLowerCase();
    const subjectNo = String(item?.subject_no || "").toLowerCase();
    const description = String(item?.description || "").toLowerCase();
    if (keyword && !pdNo.includes(keyword) && !subjectNo.includes(keyword) && !description.includes(keyword)) return false;
    if (filters.value.siteId && item?.site_id !== filters.value.siteId) return false;
    if (filters.value.status && item?.status !== filters.value.status) return false;
    return true;
  });
});

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

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;
}
</style>
