<template>
  <div class="page">
    <div class="main-content-flat unified-shell">
      <div class="filter-container unified-action-bar">
        <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-select 
              v-model="filters.fee_type" 
              :placeholder="TEXT.common.fields.type" 
              clearable
              class="filter-select-comp"
            >
              <el-option :label="TEXT.enums.financeSpecialType.TRAVEL" value="TRAVEL" />
              <el-option :label="TEXT.enums.financeSpecialType.HOTEL" value="HOTEL" />
              <el-option :label="TEXT.enums.financeSpecialType.TRANSPORT" value="TRANSPORT" />
              <el-option :label="TEXT.enums.financeSpecialType.OTHER" value="OTHER" />
            </el-select>
          </div>
          <div class="filter-item-form">
            <el-button @click="resetFilters">{{ TEXT.common.actions.reset }}</el-button>
          </div>
          <div class="filter-spacer"></div>
          <el-button type="primary" @click="goNew">
            {{ TEXT.modules.financeSpecials.newTitle }}
          </el-button>
        </el-form>
      </div>
      <div class="unified-section table-section">
        <el-table
          :data="sortedItems"
          v-loading="loading"
          style="width: 100%"
          class="ctms-table"
          @row-click="onRowClick"
          :row-class-name="specialRowClass"
        >
          <el-table-column prop="site_name" :label="TEXT.common.fields.site" min-width="160" />
          <el-table-column prop="fee_type" :label="TEXT.common.fields.type" width="120">
            <template #default="scope">
              {{ displayEnum(TEXT.enums.financeSpecialType, scope.row.fee_type) }}
            </template>
          </el-table-column>
          <el-table-column prop="occur_date" :label="TEXT.common.fields.occurDate" width="140">
            <template #default="scope">
              {{ displayDate(scope.row.occur_date) }}
            </template>
          </el-table-column>
          <el-table-column prop="staff_name" :label="TEXT.common.fields.staff" min-width="120" />
          <el-table-column :label="TEXT.common.fields.amount" width="140">
            <template #default="scope">
              {{ scope.row.amount }}
            </template>
          </el-table-column>
          <el-table-column prop="updated_at" :label="TEXT.common.labels.updatedAt" width="180">
            <template #default="scope">
              {{ displayDateTime(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="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.financeSpecials.empty }}</div>
          </template>
        </el-table>
      </div>
    </div>
  </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 { listFinanceSpecials, deleteFinanceSpecial } from "../../api/financeSpecials";
import { fetchSites } from "../../api/sites";
import { displayDate, displayDateTime, displayEnum } from "../../utils/display";
import { TEXT } from "../../locales";

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

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 specialRowClass = ({ row }: { row: any }) =>
  `${row?.id ? "clickable-row" : ""}${isInactiveSite(row?.site_name) ? " row-inactive" : ""}`.trim();
const filteredItems = computed(() => {
  const keyword = filters.site_name.trim().toLowerCase();
  return items.value.filter((item) => {
    if (keyword && !String(item?.site_name || "").toLowerCase().includes(keyword)) return false;
    if (filters.fee_type && item?.fee_type !== filters.fee_type) return false;
    return true;
  });
});
const sortedItems = computed(() =>
  [...filteredItems.value].sort((a, b) => Number(isInactiveSite(a?.site_name)) - Number(isInactiveSite(b?.site_name)))
);

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 listFinanceSpecials(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.fee_type = "";
};

const goNew = () => router.push("/finance/special/new");
const goDetail = (id: string) => router.push(`/finance/special/${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_name)) {
    ElMessage.warning("中心已停用");
    return;
  }
  const ok = await ElMessageBox.confirm(TEXT.common.confirm.delete, TEXT.common.labels.tips).catch(() => null);
  if (!ok) return;
  try {
    await deleteFinanceSpecial(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;
}

.main-content-flat {
  background: transparent;
  border: 0;
  border-radius: 0;
  box-shadow: none;
  padding: 0;
}

.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-select-comp {
  width: 140px;
}

.filter-spacer {
  flex: 1;
}

.table-section {
  padding-top: 0;
  padding-bottom: 0;
}

: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>
