<template>
  <div class="page ctms-page-shell page--flush" :class="{ 'fee-contracts-page--desktop': isDesktop }">
    <div class="overview fee-overview">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <KpiCard
            :title="`${TEXT.modules.feeContracts.totalContractAmount} (${TEXT.modules.feeContracts.centerCount} ${overview.centerCount})`"
            :value="formatAmountWan(overview.totalContractAmount)"
            unit="万元"
            :loading="loading"
            :icon="Coin"
            type="primary"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <KpiCard
            :title="TEXT.modules.feeContracts.totalPaidAmount"
            :value="formatAmountWan(overview.totalPaidAmount)"
            unit="万元"
            :loading="loading"
            :icon="Wallet"
            type="success"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <KpiCard
            :title="TEXT.modules.feeContracts.totalUnpaidAmount"
            :value="formatAmountWan(overview.totalUnpaidAmount)"
            unit="万元"
            :loading="loading"
            :icon="CircleClose"
            type="warning"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <KpiCard
            :title="TEXT.modules.feeContracts.totalVerifiedAmount"
            :value="formatAmountWan(overview.totalVerifiedAmount)"
            unit="万元"
            :loading="loading"
            :icon="CircleCheck"
            type="info"
          />
        </el-col>
      </el-row>
    </div>

    <StateError v-if="errorMessage" :description="errorMessage">
      <template #action>
        <el-button type="primary" @click="load">{{ TEXT.common.actions.retry }}</el-button>
      </template>
    </StateError>

    <StateLoading v-else-if="loading" :rows="6" />

    <div class="main-content-flat unified-shell contract-shell" v-else>
      <div class="filter-container unified-action-bar">
        <el-form :inline="true" :model="filters" class="filter-form">
          <div class="filter-item">
            <el-select v-model="filters.centerId" clearable :placeholder="TEXT.common.fields.site" class="filter-select">
              <template #prefix>
                <el-icon><Location /></el-icon>
              </template>
              <el-option
                v-for="site in sites"
                :key="site.id"
                :label="site.name || TEXT.common.fallback"
                :value="site.id"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <el-input v-model="filters.q" :placeholder="TEXT.common.placeholders.keyword" clearable class="filter-input">
               <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="filter-actions">
            <el-button @click="resetFilters">{{ TEXT.common.actions.reset }}</el-button>
          </div>
          <div class="filter-spacer"></div>
          <el-button v-if="canCreate" type="primary" @click="openCreate" class="header-action-btn">
            <el-icon class="el-icon--left"><Plus /></el-icon>
            {{ TEXT.modules.feeContracts.newTitle }}
          </el-button>
        </el-form>
      </div>
      <section class="unified-section contract-table-section section--flush-x section--flush-top section--flush-bottom">
        <el-table
          :data="sortedContracts"
          style="width: 100%"
          @row-click="onRowClick"
          :row-class-name="contractRowClass"
          class="contract-table"
          table-layout="fixed"
        >
          <el-table-column prop="center_name" :label="TEXT.common.fields.site" show-overflow-tooltip>
            <template #default="scope">
              <div class="site-cell">
                <span class="site-name">{{ scope.row.center_name || TEXT.common.fallback }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.modules.feeContracts.contractAmount" align="left">
            <template #default="scope">
              <span class="amount-text">{{ formatAmountWan(scope.row.contract_amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.modules.feeContracts.caseProgress" align="center">
            <template #default="scope">
               <el-tag effect="plain" type="info">
                {{ displayCases(scope.row.contract_cases, scope.row.actual_cases) }}
               </el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.modules.feeContracts.paidSummary">
            <template #default="scope">
              <div class="summary-line">
                <span>{{ TEXT.modules.feeContracts.paidTotal }}</span>
                <span class="amount-highlight success">{{ formatAmountWan(scope.row.paid_total) }}</span>
              </div>
              <div class="summary-line">
                <span>{{ TEXT.modules.feeContracts.unpaidBalance }}</span>
                <span class="amount-highlight warning" v-if="scope.row.unpaid_balance > 0">{{ formatAmountWan(scope.row.unpaid_balance) }}</span>
                <span class="amount-muted" v-else>0.00</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.modules.feeContracts.verifySummary">
            <template #default="scope">
              <div class="summary-line">
                <span>{{ TEXT.modules.feeContracts.verifiedTotal }}</span>
                <span class="amount-highlight info">{{ formatAmountWan(scope.row.verified_total) }}</span>
              </div>
              <div class="summary-line">
                <span>{{ TEXT.modules.feeContracts.unverifiedBalance }}</span>
                <span class="amount-highlight warning" v-if="scope.row.unverified_balance > 0">{{ formatAmountWan(scope.row.unverified_balance) }}</span>
                 <span class="amount-muted" v-else>0.00</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.modules.feeContracts.recentDates">
             <template #default="scope">
              <div class="date-line">
                <span class="date-label">{{ TEXT.modules.feeContracts.lastPaid }}</span>
                <span class="date-value">{{ displayDate(scope.row.last_paid_date) }}</span>
              </div>
              <div class="date-line">
                <span class="date-label">{{ TEXT.modules.feeContracts.lastVerified }}</span>
                <span class="date-value">{{ displayDate(scope.row.last_verified_date) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="canUpdate || canDelete" :label="TEXT.common.labels.actions" align="center">
            <template #default="scope">
              <el-button
                v-if="canUpdate"
                link
                type="primary"
                size="small"
                :disabled="isInactiveSite(scope.row.center_id)"
                @click.stop="openEdit(scope.row)"
              >
                {{ TEXT.common.actions.edit }}
              </el-button>
              <el-button
                v-if="canDelete"
                link
                type="danger"
                size="small"
                :disabled="isInactiveSite(scope.row.center_id)"
                @click.stop="remove(scope.row)"
              >
                {{ TEXT.common.actions.delete }}
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <div class="table-empty">{{ TEXT.modules.feeContracts.empty }}</div>
          </template>
        </el-table>
      </section>
    </div>

    <ContractFeeEditorDrawer
      v-model="drawerVisible"
      :contract-id="editingId || undefined"
      :sites="sites"
      :initial-center-id="study.currentSite?.id || ''"
      @saved="handleEditorSaved"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Coin, Wallet, CircleCheck, CircleClose, Plus, Location, Search } from "@element-plus/icons-vue";
import { deleteContractFee, listContractFees } from "../../api/feeContracts";
import { fetchSites } from "../../api/sites";
import { useStudyStore } from "../../store/study";
import { usePermission } from "../../utils/permission";
import { displayDate } from "../../utils/display";
import StateLoading from "../../components/StateLoading.vue";
import StateError from "../../components/StateError.vue";
import KpiCard from "../../components/KpiCard.vue";
import ContractFeeEditorDrawer from "./ContractFeeEditorDrawer.vue";
import { TEXT } from "../../locales";
import { isTauriRuntime } from "../../runtime";

const router = useRouter();
const study = useStudyStore();
const isDesktop = isTauriRuntime();
const { can } = usePermission();
const canCreate = computed(() => can("fees.contract.create"));
const canUpdate = computed(() => can("fees.contract.update"));
const canDelete = computed(() => can("fees.contract.delete"));

const loading = ref(false);
const errorMessage = ref("");
const contracts = ref<any[]>([]);
const sites = ref<any[]>([]);
const drawerVisible = ref(false);
const editingId = ref("");
const siteActiveMap = computed(() => {
  const map: Record<string, boolean> = {};
  sites.value.forEach((site) => {
    if (site?.id) map[site.id] = !!site.is_active;
  });
  return map;
});
const isInactiveSite = (siteId?: string) => !!siteId && siteActiveMap.value[siteId] === false;
const filteredContracts = computed(() => {
  const keyword = filters.q.trim().toLowerCase();
  return contracts.value.filter((item) => {
    if (filters.centerId && item?.center_id !== filters.centerId) return false;
    if (keyword) {
      const fields = [item?.center_name, item?.contract_no, item?.contract_name];
      const matched = fields.some((field) => String(field || "").toLowerCase().includes(keyword));
      if (!matched) return false;
    }
    return true;
  });
});
const sortedContracts = computed(() =>
  [...filteredContracts.value].sort((a, b) => Number(isInactiveSite(a?.center_id)) - Number(isInactiveSite(b?.center_id)))
);
const contractRowClass = ({ row }: { row: any }) =>
  `${row?.id ? "clickable-row" : ""}${isInactiveSite(row?.center_id) ? " row-inactive" : ""}`.trim();

const filters = reactive({
  centerId: study.currentSite?.id || "",
  q: "",
});

const toNumber = (value: any) => {
  const numberValue = Number(value);
  return Number.isNaN(numberValue) ? 0 : numberValue;
};

const overview = computed(() => {
  const totals = filteredContracts.value.reduce(
    (acc, item) => {
      acc.totalContractAmount += toNumber(item.contract_amount);
      acc.totalPaidAmount += toNumber(item.paid_total);
      acc.totalUnpaidAmount += toNumber(item.unpaid_balance);
      acc.totalVerifiedAmount += toNumber(item.verified_total);
      return acc;
    },
    {
      totalContractAmount: 0,
      totalPaidAmount: 0,
      totalUnpaidAmount: 0,
      totalVerifiedAmount: 0,
    }
  );
  return {
    ...totals,
    centerCount: filteredContracts.value.length,
  };
});

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;
  errorMessage.value = "";
  try {
    const { data } = await listContractFees({ study_id: studyId });
    contracts.value = data?.data || [];
  } catch (e: any) {
    errorMessage.value = e?.response?.data?.message || TEXT.common.messages.loadFailed;
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => {
  filters.centerId = "";
  filters.q = "";
};

const openCreate = () => {
  if (!canCreate.value) {
    ElMessage.warning("权限不足");
    return;
  }
  editingId.value = "";
  drawerVisible.value = true;
};

const openEdit = async (row: any) => {
  if (!row?.id) return;
  if (!canUpdate.value) {
    ElMessage.warning("权限不足");
    return;
  }
  if (isInactiveSite(row?.center_id)) {
    ElMessage.warning("中心已停用");
    return;
  }
  editingId.value = row.id;
  drawerVisible.value = true;
};

const goDetail = (id: string) => router.push(`/fees/contracts/${id}`);
const onRowClick = (row: any) => {
  if (!row?.id) return;
  goDetail(row.id);
};

const remove = async (row: any) => {
  if (!row?.id) return;
  if (!canDelete.value) {
    ElMessage.warning("权限不足");
    return;
  }
  if (isInactiveSite(row?.center_id)) {
    ElMessage.warning("中心已停用");
    return;
  }
  const ok = await ElMessageBox.confirm(TEXT.common.confirm.delete, TEXT.common.labels.tips).catch(() => null);
  if (!ok) return;
  try {
    await deleteContractFee(row.id);
    ElMessage.success(TEXT.common.messages.deleteSuccess);
    load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.deleteFailed);
  }
};

const handleEditorSaved = async () => {
  await load();
};

const displayCases = (contractCases: any, actualCases: any) => {
  const contractValue = Number(contractCases ?? 0);
  const actualValue = Number(actualCases ?? 0);
  if (Number.isNaN(contractValue) || Number.isNaN(actualValue)) {
    return TEXT.common.fallback;
  }
  return `${actualValue}/${contractValue}`;
};

const formatAmountWan = (value: any) => {
  const numberValue = Number(value);
  if (Number.isNaN(numberValue)) return TEXT.common.fallback;
  return (numberValue / 10000).toFixed(2);
};

watch(() => filters.centerId, (val: string) => {
  if (val) {
    const matched = sites.value.find(s => s.id === val);
    if (matched) study.setCurrentSite(matched);
  } else {
    study.setCurrentSite(null);
  }
});

watch(() => study.currentSite, (newSite: any) => {
  filters.centerId = newSite?.id || "";
});

watch(
  () => study.currentStudy?.id,
  async () => {
    filters.centerId = study.currentSite?.id || "";
    filters.q = "";
    drawerVisible.value = false;
    await loadSites();
    await load();
  }
);

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

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

.overview {
  margin: 0;
}

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

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

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

.filter-actions {
  margin-bottom: 0 !important;
}

.filter-spacer {
  flex: 1;
}

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

.site-cell {
  font-weight: 500;
  color: var(--ctms-text-main);
}

.amount-text {
  font-family: var(--el-font-family);
  font-weight: 500;
}

.summary-line {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 13px;
  margin-bottom: 4px;
  color: var(--ctms-text-regular);
  gap: 8px;
}

.summary-line:last-child {
  margin-bottom: 0;
}

.summary-line span:first-child {
  color: var(--ctms-text-secondary);
}

.amount-highlight {
  font-weight: 600;
  font-family: var(--el-font-family);
}

.summary-line .amount-highlight,
.summary-line .amount-muted {
  text-align: left;
}

.amount-highlight.success { color: var(--el-color-success); }
.amount-highlight.warning { color: var(--el-color-warning); }
.amount-highlight.info { color: var(--el-color-info); }
.amount-muted { color: var(--ctms-text-placeholder); }

.date-line {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 12px;
  margin-bottom: 2px;
  gap: 8px;
}

.date-label {
  color: var(--ctms-text-secondary);
}

.date-value {
  color: var(--ctms-text-regular);
  font-family: var(--el-font-family);
}

.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;
}

.fee-contracts-page--desktop {
  height: 100%;
  min-height: 0;
  overflow: hidden;
  gap: 8px;
}

.fee-contracts-page--desktop .fee-overview {
  flex: 0 0 auto;
}

.fee-contracts-page--desktop .contract-shell {
  display: flex;
  flex: 1 1 0;
  min-height: 0;
  flex-direction: column;
}

.fee-contracts-page--desktop .contract-table-section {
  flex: 1 1 0;
  min-height: 0;
  background: var(--ctms-bg-card);
}

.fee-contracts-page--desktop .table-empty {
  min-height: 132px;
  letter-spacing: 0;
}

.fee-contracts-page--desktop :deep(.kpi-card) {
  min-height: 104px;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: none;
  transform: none;
}

.fee-contracts-page--desktop :deep(.kpi-card:hover) {
  box-shadow: none;
  transform: none;
}

.fee-contracts-page--desktop :deep(.kpi-badge) {
  margin-bottom: 8px;
  padding: 3px 9px;
  border-radius: 5px;
}

.fee-contracts-page--desktop :deep(.kpi-title) {
  overflow: hidden;
  font-size: 15px;
  line-height: 1.25;
  letter-spacing: 0;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.fee-contracts-page--desktop :deep(.kpi-footer) {
  padding-top: 8px;
}

.fee-contracts-page--desktop :deep(.kpi-value) {
  font-size: 30px;
  letter-spacing: 0;
}

.fee-contracts-page--desktop :deep(.kpi-unit) {
  font-size: 13px;
}

</style>

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

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