<template>
  <div class="page ctms-page-shell page--flush">
    <div class="overview">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <KpiCard
            :title="TEXT.modules.feeSpecials.totalAmount"
            :value="formatAmount(overview.totalAmount)"
            unit="元"
            :loading="loading"
            :icon="Coin"
            type="primary"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <KpiCard
            :title="TEXT.modules.feeSpecials.paidAmount"
            :value="formatAmount(overview.paidAmount)"
            unit="元"
            :loading="loading"
            :icon="Wallet"
            type="success"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <KpiCard
            :title="TEXT.modules.feeSpecials.verifiedAmount"
            :value="formatAmount(overview.verifiedAmount)"
            unit="元"
            :loading="loading"
            :icon="CircleCheck"
            type="info"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <KpiCard
            :title="TEXT.modules.feeSpecials.attachmentTotal"
            :value="overview.attachmentTotal"
            :loading="loading"
            :icon="Document"
            type="warning"
          />
        </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" v-else>
      <div class="filter-container unified-action-bar">
        <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-select v-model="filters.category" clearable :placeholder="TEXT.common.fields.category" class="filter-select">
              <template #prefix>
                <el-icon><Menu /></el-icon>
              </template>
              <el-option v-for="option in categoryOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="" class="filter-item">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              unlink-panels
              value-format="YYYY-MM-DD"
              :start-placeholder="TEXT.common.placeholders.startDate"
              :end-placeholder="TEXT.common.placeholders.endDate"
              class="filter-date"
            />
          </el-form-item>
          <el-form-item class="filter-actions">
            <el-button @click="resetFilters">{{ TEXT.common.actions.reset }}</el-button>
          </el-form-item>
          <div class="filter-spacer"></div>
          <el-button type="primary" :disabled="!canWrite" @click="goNew" class="header-action-btn">
            <el-icon class="el-icon--left"><Plus /></el-icon>
            {{ TEXT.modules.feeSpecials.newTitle }}
          </el-button>
        </el-form>
      </div>
      <section class="unified-section special-expense-table-section section--flush-x section--flush-top section--flush-bottom">
        <el-table
          :data="sortedExpenses"
          style="width: 100%"
          @row-click="onRowClick"
          :row-class-name="expenseRowClass"
          class="special-expense-table"
        >
          <el-table-column :label="TEXT.common.fields.occurDate" width="140">
            <template #default="scope">
              <span class="date-text">{{ displayDate(scope.row.happen_date) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.common.fields.site" min-width="160">
            <template #default="scope">
              <span class="site-text">{{ scope.row.center_name || TEXT.common.fallback }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.common.fields.category" width="140">
            <template #default="scope">
              <el-tag size="small" :type="getCategoryType(scope.row.category)" effect="light" class="category-tag">
                {{ displayEnum(TEXT.enums.feeSpecialCategory, scope.row.category) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.common.fields.amount" width="110" align="right">
            <template #default="scope">
              <span class="amount-text">{{ formatAmount(scope.row.amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="description" :label="TEXT.common.fields.remark" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.description || TEXT.common.fallback }}
            </template>
          </el-table-column>
          <el-table-column width="140" align="center" :label="TEXT.common.fields.status">
            <template #default="scope">
              <el-tooltip :content="scope.row.is_paid ? `${TEXT.modules.feeSpecials.isPaid} (${displayDate(scope.row.paid_date)})` : TEXT.modules.feeSpecials.unpaid" placement="top">
                <el-icon :class="scope.row.is_paid ? 'status-icon success' : 'status-icon muted'"><Wallet /></el-icon>
              </el-tooltip>
              <el-tooltip :content="scope.row.is_verified ? `${TEXT.modules.feeSpecials.isVerified} (${displayDate(scope.row.verified_date)})` : TEXT.modules.feeSpecials.unverified" placement="top">
                <el-icon :class="scope.row.is_verified ? 'status-icon info' : 'status-icon muted'"><CircleCheck /></el-icon>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.modules.feeSpecials.attachmentCount" width="120" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.attachments_count > 0" effect="plain" type="info" round size="small">
                {{ scope.row.attachments_count }}
              </el-tag>
              <span v-else class="text-muted">-</span>
            </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="!canWrite || 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.feeSpecials.empty }}</div>
          </template>
        </el-table>
      </section>
    </div>
  </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, Document, Plus, Location, Menu } from "@element-plus/icons-vue";
import { deleteSpecialExpense, listSpecialExpenses } from "../../api/feeSpecials";
import { fetchSites } from "../../api/sites";
import { useStudyStore } from "../../store/study";
import { usePermission } from "../../utils/permission";
import { displayDate, displayEnum } from "../../utils/display";
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.special.write"));

const loading = ref(false);
const errorMessage = ref("");
const expenses = ref<any[]>([]);
const sites = ref<any[]>([]);
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 expenseRowClass = ({ row }: { row: any }) =>
  `${row?.id ? "clickable-row" : ""}${isInactiveSite(row?.center_id) ? " row-inactive" : ""}`.trim();
const filteredExpenses = computed(() => {
  const [dateFrom, dateTo] = filters.dateRange || [];
  return expenses.value.filter((item) => {
    if (filters.centerId && item?.center_id !== filters.centerId) return false;
    if (filters.category && item?.category !== filters.category) return false;
    if (dateFrom || dateTo) {
      const value = item?.happen_date;
      if (!value) return false;
      if (dateFrom && value < dateFrom) return false;
      if (dateTo && value > dateTo) return false;
    }
    return true;
  });
});
const sortedExpenses = computed(() =>
  [...filteredExpenses.value].sort((a, b) => Number(isInactiveSite(a?.center_id)) - Number(isInactiveSite(b?.center_id)))
);

const filters = reactive({
  centerId: study.currentSite?.id || "",
  category: "",
  dateRange: [] as string[],
});

const categoryOptions = Object.keys(TEXT.enums.feeSpecialCategory).map((value) => ({
  value,
  label: (TEXT.enums.feeSpecialCategory as any)[value],
}));

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

const overview = computed(() => {
  const totals = filteredExpenses.value.reduce(
    (acc, item) => {
      acc.totalAmount += toNumber(item.amount);
      if (item.is_paid) acc.paidAmount += toNumber(item.amount);
      if (item.is_verified) acc.verifiedAmount += toNumber(item.amount);
      acc.attachmentTotal += toNumber(item.attachments_count);
      return acc;
    },
    {
      totalAmount: 0,
      paidAmount: 0,
      verifiedAmount: 0,
      attachmentTotal: 0,
    }
  );
  return {
    ...totals,
  };
});

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 listSpecialExpenses({ projectId });
    expenses.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.category = "";
  filters.dateRange = [];
};

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

const remove = async (row: any) => {
  if (!row?.id || !canWrite.value) 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 deleteSpecialExpense(row.id);
    ElMessage.success(TEXT.common.messages.deleteSuccess);
    load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.deleteFailed);
  }
};

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

const getCategoryType = (category: string) => {
  if (category === 'travel') return 'warning';
  if (category === 'meeting') return 'success';
  if (category === 'material') return 'primary';
  return 'info';
};

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 || "";
});

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

.filter-date {
  width: 220px;
}

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

.filter-spacer {
  flex: 1;
}

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

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

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

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

.category-tag {
  font-weight: 500;
}

.status-icon {
  font-size: 18px;
  margin: 0 6px;
  outline: none;
}

.status-icon.success { color: var(--el-color-success); }
.status-icon.info { color: var(--el-color-info); }
.status-icon.muted { color: var(--ctms-border-color); opacity: 0.6; }

.text-muted {
  color: var(--ctms-text-placeholder);
}

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