<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1 class="page-title">受试者管理</h1>
        <p class="page-subtitle">受试者、访视与 AE 统一管理</p>
      </div>
      <el-button type="primary" @click="goNew">新增受试者</el-button>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filters">
        <el-form-item label="编号">
          <el-input v-model="filters.subject_no" placeholder="输入受试者编号" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable>
            <el-option label="筛选" value="SCREENING" />
            <el-option label="入组" value="ENROLLED" />
            <el-option label="完成" value="COMPLETED" />
            <el-option label="退出" value="DROPPED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="load">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-table :data="items" v-loading="loading" style="width: 100%">
        <el-table-column prop="subject_no" label="受试者编号" min-width="140" />
        <el-table-column label="分中心" min-width="160">
          <template #default="scope">{{ siteMap[scope.row.site_id] || "—" }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column prop="enrollment_date" label="入组日期" width="140">
          <template #default="scope">{{ displayDate(scope.row.enrollment_date) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="goDetail(scope.row.id)">详情</el-button>
            <el-button link type="primary" size="small" @click="goEdit(scope.row.id)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <StateEmpty v-if="!loading && items.length === 0" description="暂无受试者记录" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useStudyStore } from "../../store/study";
import { fetchSubjects } from "../../api/subjects";
import { fetchSites } from "../../api/sites";
import { displayDate } from "../../utils/display";
import StateEmpty from "../../components/StateEmpty.vue";

const router = useRouter();
const study = useStudyStore();
const loading = ref(false);
const items = ref<any[]>([]);
const siteMap = ref<Record<string, string>>({});
const filters = reactive({
  subject_no: "",
  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 || [];
    siteMap.value = list.reduce((acc: Record<string, string>, site: any) => {
      acc[site.id] = site.name;
      return acc;
    }, {});
  } catch {
    siteMap.value = {};
  }
};

const load = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  loading.value = true;
  try {
    const { data } = await fetchSubjects(studyId, {
      subject_no: filters.subject_no || undefined,
      status_filter: filters.status || undefined,
    });
    items.value = Array.isArray(data) ? data : data.items || [];
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "加载失败");
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => {
  filters.subject_no = "";
  filters.status = "";
  load();
};

const goNew = () => router.push("/subjects/new");
const goDetail = (id: string) => router.push(`/subjects/${id}`);
const goEdit = (id: string) => router.push(`/subjects/${id}/edit`);

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

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

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
}

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

.filter-card :deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
