<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1 class="page-title">{{ TEXT.modules.feeContracts.title }}</h1>
        <p class="page-subtitle">{{ TEXT.modules.feeContracts.subtitle }}</p>
      </div>
      <el-button type="primary" :disabled="!canWrite" @click="goNew" class="header-action-btn">
        <el-icon class="el-icon--left"><Plus /></el-icon>
        {{ TEXT.modules.feeContracts.newTitle }}
      </el-button>
    </div>

    <div class="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>

    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="" 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>
        </el-form-item>
        <el-form-item label="" 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>
        </el-form-item>
        <el-form-item class="filter-actions">
          <el-button type="primary" @click="load">{{ TEXT.common.actions.search }}</el-button>
          <el-button @click="resetFilters">{{ TEXT.common.actions.reset }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <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" />

    <el-card v-else class="table-card" shadow="never">
      <el-table :data="contracts" style="width: 100%" @row-click="onRowClick" :header-cell-style="{ background: '#f8f9fb' }">
        <el-table-column prop="center_name" :label="TEXT.common.fields.site" min-width="180">
          <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" width="160" align="right">
          <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" min-width="150" 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" min-width="180">
          <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" min-width="180">
          <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" min-width="200">
           <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 :label="TEXT.common.fields.remark" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.remark || TEXT.common.fallback }}
          </template>
        </el-table-column>
        <el-table-column :label="TEXT.common.actions.delete" width="120">
          <template #default="scope">
            <el-button
              link
              type="danger"
              size="small"
              :disabled="!canWrite"
              @click.stop="remove(scope.row)"
            >
              {{ TEXT.common.actions.delete }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <StateEmpty v-if="contracts.length === 0" :description="TEXT.modules.feeContracts.empty" />
    </el-card>
  </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 { 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 StateEmpty from "../../components/StateEmpty.vue";
import StateLoading from "../../components/StateLoading.vue";
import StateError from "../../components/StateError.vue";
import KpiCard from "../../components/KpiCard.vue";
import { TEXT } from "../../locales";

const router = useRouter();
const study = useStudyStore();
const { can } = usePermission();
const canWrite = computed(() => can("fees.contract.write"));

const loading = ref(false);
const errorMessage = ref("");
const contracts = ref<any[]>([]);
const sites = ref<any[]>([]);

const filters = reactive({
  centerId: "",
  q: "",
});

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

const overview = computed(() => {
  const totals = contracts.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: contracts.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 projectId = study.currentStudy?.id;
  if (!projectId) return;
  loading.value = true;
  errorMessage.value = "";
  try {
    const { data } = await listContractFees({
      projectId,
      centerId: filters.centerId || undefined,
      q: filters.q || undefined,
    });
    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 = "";
  load();
};

const goNew = () => router.push("/fees/contracts/new");
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 || !canWrite.value) 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 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);
};

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

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

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: var(--ctms-text-main);
  letter-spacing: -0.5px;
}

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

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

.overview {
  margin-bottom: 4px;
}

.filter-card {
  border: none;
  background-color: transparent;
  padding: 0;
}

.filter-card :deep(.el-card__body) {
  padding: 0;
}

.filter-form {
  display: flex;
  gap: 12px;
  align-items: center;
  background: white;
  padding: 16px;
  border-radius: 12px;
  border: 1px solid var(--ctms-border-color);
}

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

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

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

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

.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: space-between;
  align-items: center;
  font-size: 13px;
  margin-bottom: 4px;
  color: var(--ctms-text-regular);
}

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

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

.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: space-between;
  font-size: 12px;
  margin-bottom: 2px;
}

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

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