<template>
  <div class="page">

    <el-card shadow="never" class="main-content-card">
      <div class="filter-container">
        <el-form :inline="true" :model="filters" class="filter-form">
          <el-form-item label="" class="filter-item-form">
            <el-input
              v-model="filters.keyword"
              :placeholder="TEXT.modules.subjectManagement.screeningNo"
              clearable
              class="filter-input-comp"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="" 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 label="" 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>
          <div class="filter-spacer"></div>
          <el-button type="primary" @click="goNew" class="header-action-btn">
            <el-icon class="el-icon--left"><Plus /></el-icon>
            {{ TEXT.common.actions.add }}{{ TEXT.modules.subjectManagement.subjectLabel }}
          </el-button>
        </el-form>
      </div>
      <el-table
        :data="pagedItems"
        v-loading="loading"
        style="width: 100%"
        class="ctms-table"
        :row-class-name="subjectRowClass"
        @row-click="onRowClick"
      >
        <el-table-column prop="subject_no" :label="TEXT.modules.subjectManagement.screeningNo" min-width="160">
          <template #default="scope">
            <div class="subject-info-cell">
              <span class="subject-no">{{ scope.row.subject_no || TEXT.common.fallback }}</span>
              <span v-if="scope.row.has_ae" class="ae-badge">AE</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="TEXT.common.fields.site" min-width="160">
          <template #default="scope">{{ siteMap[scope.row.site_id] || TEXT.common.fallback }}</template>
        </el-table-column>
        <el-table-column prop="consent_date" :label="TEXT.common.fields.consentDate" width="140">
          <template #default="scope">{{ displayDate(scope.row.consent_date) }}</template>
        </el-table-column>
        <el-table-column prop="status" :label="TEXT.common.fields.status" width="120">
          <template #default="scope">{{ displayEnum(TEXT.enums.subjectStatus, scope.row.status) }}</template>
        </el-table-column>
        <el-table-column prop="enrollment_date" :label="TEXT.common.fields.enrollmentDate" width="140">
          <template #default="scope">{{ displayDate(scope.row.enrollment_date) }}</template>
        </el-table-column>
        <el-table-column prop="completion_date" :label="TEXT.common.fields.completionDate" width="140">
          <template #default="scope">{{ displayDate(scope.row.completion_date) }}</template>
        </el-table-column>
        <el-table-column :label="TEXT.common.labels.actions" width="120">
          <template #default="scope">
            <el-button
              link
              type="danger"
              size="small"
              :disabled="isInactiveSite(scope.row.site_id)"
              @click.stop="remove(scope.row)"
            >
              {{ TEXT.common.actions.delete }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="filteredItems.length"
          layout="total, prev, pager, next, sizes"
        />
      </div>
      <StateEmpty v-if="!loading && sortedItems.length === 0" :description="TEXT.modules.subjectManagement.empty" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Location, CircleCheck, Plus } from "@element-plus/icons-vue";
import { useStudyStore } from "../../store/study";
import { deleteSubject, fetchSubjects } from "../../api/subjects";
import { fetchSites } from "../../api/sites";
import { displayDate, 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 siteActiveMap = ref<Record<string, boolean>>({});
const filters = ref({
  keyword: "",
  siteId: study.currentSite?.id || "",
  status: "",
});
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
});
const statusOptions = Object.entries(TEXT.enums.subjectStatus).map(([value, label]) => ({ value, label }));
const resetFilters = () => {
  filters.value.keyword = "";
  filters.value.siteId = "";
  filters.value.status = "";
};
const loadSites = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  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;
    }, {});
    siteActiveMap.value = list.reduce((acc: Record<string, boolean>, site: any) => {
      acc[site.id] = !!site.is_active;
      return acc;
    }, {});
  } catch {
    siteMap.value = {};
    siteActiveMap.value = {};
  }
};

const load = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  loading.value = true;
  try {
    const { data } = await fetchSubjects(studyId);
    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 goNew = () => router.push("/subjects/new");
const goDetail = (id: string) => router.push(`/subjects/${id}`);
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 (isInactiveSite(row?.site_id)) {
    ElMessage.warning("中心已停用");
    return;
  }
  const ok = await ElMessageBox.confirm(TEXT.common.confirm.delete, TEXT.common.labels.tips).catch(() => null);
  if (!ok) return;
  try {
    await deleteSubject(studyId, row.id);
    ElMessage.success(TEXT.common.messages.deleteSuccess);
    load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.deleteFailed);
  }
};

const isInactiveSite = (siteId?: string) => !!siteId && siteActiveMap.value[siteId] === false;
const filteredItems = computed(() => {
  const keyword = filters.value.keyword.trim().toLowerCase();
  return items.value.filter((item) => {
    if (keyword && !String(item?.subject_no || "").toLowerCase().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 sortedItems = computed(() =>
  [...filteredItems.value].sort((a, b) => Number(isInactiveSite(a?.site_id)) - Number(isInactiveSite(b?.site_id)))
);
const pagedItems = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize;
  const end = start + pagination.value.pageSize;
  return sortedItems.value.slice(start, end);
});
const subjectRowClass = ({ row }: { row: any }) =>
  `${row?.id ? "clickable-row" : ""}${isInactiveSite(row?.site_id) ? " row-inactive" : ""}`.trim();

watch(
  () => [filters.value.keyword, filters.value.siteId, filters.value.status, pagination.value.pageSize],
  () => {
    pagination.value.currentPage = 1;
  }
);

watch(
  () => filteredItems.value.length,
  (total) => {
    const maxPage = Math.max(1, Math.ceil(total / pagination.value.pageSize));
    if (pagination.value.currentPage > maxPage) {
      pagination.value.currentPage = maxPage;
    }
  }
);

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

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

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

.main-content-card :deep(.el-card__body) {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

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

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

.filter-select-comp,
.filter-input-comp {
  width: 140px;
}

.filter-spacer {
  flex: 1;
}

.header-action-btn {
  height: 36px;
  padding: 0 20px;
  border-radius: 8px;
}

.subject-info-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.subject-no {
  font-weight: 600;
  color: var(--ctms-text-main);
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}

.ae-badge {
  display: inline-flex;
  align-items: center;
  background: linear-gradient(135deg, #fff1f2 0%, #ffe4e6 100%);
  color: #be123c;
  border: 1px solid rgba(225, 29, 72, 0.2);
  padding: 2px 6px;
  height: 18px;
  line-height: normal;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.02em;
  box-shadow: 0 1px 2px rgba(225, 29, 72, 0.05);
}

.ae-badge::before {
  content: "";
  display: inline-block;
  width: 5px;
  height: 5px;
  background-color: #e11d48;
  border-radius: 50%;
  margin-right: 4px;
}

.table-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

.table-card {
  border-radius: 12px;
  border: 1px solid var(--ctms-border-color);
  overflow: hidden;
}

.page-subtitle {
  margin: 6px 0 0;
  font-size: 13px;
  color: var(--ctms-text-secondary);
}

</style>

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

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