<template>
  <div class="study-home-container unified-shell" v-if="study.currentStudy">
    <!-- 概览头部 -->
    <div class="home-header">
      <div class="header-content">
        <h1 class="welcome-title">{{ TEXT.modules.projectOverview.title }}</h1>
        <p class="page-subtitle">{{ TEXT.modules.projectOverview.subtitle }}</p>
        <p class="study-info">
          <span class="study-name">{{ study.currentStudy.name }}</span>
          <span class="study-divider">/</span>
          <span class="study-code">{{ study.currentStudy.code }}</span>
        </p>
      </div>
      <div class="header-meta">
        <el-tag effect="plain" class="role-tag">{{ TEXT.common.labels.role }}: {{ roleLabel }}</el-tag>
      </div>
    </div>

    <!-- 数据指标网格 -->
    <div class="stats-grid">
      <div class="stats-item">
        <KpiCard
          :title="TEXT.modules.projectOverview.kpiProgress"
          :value="progress?.milestones_done ?? 0"
          :unit="` / ${progress?.milestones_total ?? 0}`"
          :subtext="milestoneCompletionRate"
          :loading="loading.progress"
          :icon="List"
        />
      </div>
      <div class="stats-item">
        <KpiCard 
          :title="TEXT.modules.projectOverview.kpiOverdueAes" 
          :value="overdueAes" 
          :unit="TEXT.common.units.case"
          :subtext="TEXT.modules.projectOverview.kpiOverdueAesHint"
          :loading="loading.overdueAes" 
          :icon="Warning"
        />
      </div>
      <div v-if="canReadFinanceContracts" class="stats-item">
        <KpiCard
          :title="TEXT.modules.projectOverview.kpiFinanceTotal"
          :value="formatAmount(financeSummary?.total_amount ?? 0)"
          :subtext="`${TEXT.modules.projectOverview.kpiFinancePaid}：¥${formatAmount(financeSummary?.paid_amount ?? 0)}`"
          :loading="loading.finance"
          :icon="Money"
        />
      </div>
    </div>

    <!-- 通知/警告 -->
    <el-alert
      v-if="overdueAes > 0"
      type="warning"
      :title="TEXT.modules.projectOverview.alertWarning"
      show-icon
      :closable="false"
      class="home-alert"
    />
    <el-alert
      v-else
      type="success"
      :title="TEXT.modules.projectOverview.alertOk"
      show-icon
      :closable="false"
      class="home-alert"
    />

    <!-- 通知 -->
    <el-card class="notifications-card unified-shell">
      <div class="notifications-header">
        <span class="notifications-title">{{ TEXT.modules.projectOverview.notificationsTitle }}</span>
        <span class="notifications-subtitle">{{ TEXT.modules.projectOverview.notificationsSubtitle }}</span>
      </div>
      <el-skeleton v-if="loading.notifications" :rows="3" animated />
      <StateEmpty v-else-if="!notifications.length" :description="TEXT.modules.projectOverview.notificationsEmpty" />
      <div v-else class="notification-list">
        <div class="notification-item" v-for="item in notifications" :key="item.id">
          <div class="notification-main">
            <div class="notification-title">
              <span class="notification-doc">{{ item.document_title }}</span>
              <span class="notification-version">V{{ item.version_no }}</span>
            </div>
            <div class="notification-meta">
              <span class="notification-time">{{ formatDate(item.effective_at || item.created_at) }}</span>
              <span v-if="item.change_summary" class="notification-summary">{{ item.change_summary }}</span>
            </div>
          </div>
          <el-button link type="primary" @click="openDocument(item.document_id)">
            {{ TEXT.common.actions.view }}
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 快捷模块 -->
    <div class="quick-nav-section">
      <QuickActions />
    </div>
  </div>
  
  <div v-else class="empty-state-container">
    <StateEmpty :description="TEXT.common.empty.selectProject" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useAuthStore } from "../store/auth";
import { useStudyStore } from "../store/study";
import { fetchFinanceSummary, fetchOverdueAesCount, fetchProgress } from "../api/dashboard";
import { listNotifications } from "../api/notifications";
import KpiCard from "../components/KpiCard.vue";
import QuickActions from "../components/QuickActions.vue";
import { List, Warning, Money } from "@element-plus/icons-vue";
import StateEmpty from "../components/StateEmpty.vue";
import { getProjectRole, isSystemAdmin } from "../utils/roles";
import { isApiPermissionAllowed } from "../utils/apiPermissionValue";
import { useRoleTemplateMeta } from "../composables/useRoleTemplateMeta";
import { TEXT } from "../locales";
import type { NotificationItem } from "../types/notifications";
import { useRouter } from "vue-router";

const auth = useAuthStore();
const study = useStudyStore();
const router = useRouter();
const { roleLabel: displayRoleLabel, loadRoleTemplates } = useRoleTemplateMeta();

const progress = ref<any>(null);
const financeSummary = ref<any>(null);
const overdueAes = ref<number>(0);
const notifications = ref<NotificationItem[]>([]);

const loading = ref({
  progress: false,
  finance: false,
  overdueAes: false,
  notifications: false,
});

const milestoneCompletionRate = computed(() => {
  const total = progress.value?.milestones_total ?? 0;
  if (!total) return TEXT.modules.projectOverview.noMilestones;
  const rate = (progress.value?.milestones_done ?? 0) / total;
  return TEXT.modules.projectOverview.progressLabel.replace("{rate}", `${(rate * 100).toFixed(0)}%`);
});

const projectRole = computed(() => {
  if (isSystemAdmin(auth.user)) return "ADMIN";
  return getProjectRole(study.currentStudy, study.currentStudyRole);
});
const roleLabel = computed(() => displayRoleLabel(projectRole.value));
const canReadFinanceContracts = computed(() => {
  if (isSystemAdmin(auth.user)) return true;
  const role = projectRole.value;
  if (!role) return false;
  return isApiPermissionAllowed(study.currentPermissions?.[role]?.["fees_contracts:read"]);
});

const formatAmount = (val: number) => {
  return new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2 }).format(val);
};

const loadData = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;

  loading.value.progress = true;
  loading.value.finance = canReadFinanceContracts.value;
  loading.value.overdueAes = true;
  loading.value.notifications = true;
  try {
    const [pRes, fRes, aesRes, nRes] = await Promise.allSettled([
      fetchProgress(studyId),
      canReadFinanceContracts.value ? fetchFinanceSummary(studyId) : Promise.resolve(null),
      fetchOverdueAesCount(studyId),
      listNotifications(studyId, { limit: 5 }),
    ]);

    if (pRes.status === "fulfilled") progress.value = pRes.value.data;
    if (fRes.status === "fulfilled" && fRes.value) financeSummary.value = fRes.value.data;
    if (aesRes.status === "fulfilled") overdueAes.value = aesRes.value.data?.total ?? 0;
    if (nRes.status === "fulfilled") notifications.value = nRes.value.data || [];
  } finally {
    loading.value.progress = false;
    loading.value.finance = false;
    loading.value.overdueAes = false;
    loading.value.notifications = false;
  }
};

const resetData = () => {
  progress.value = null;
  financeSummary.value = null;
  overdueAes.value = 0;
  notifications.value = [];
};

const formatDate = (value?: string | null) => {
  if (!value) return TEXT.common.fallback;
  return value.replace("T", " ").replace("Z", "").split(".")[0];
};

const openDocument = (documentId: string) => {
  router.push(`/documents/${documentId}`);
};

onMounted(() => {
  loadRoleTemplates();
  loadData();
});

watch(
  () => study.currentStudy?.id,
  () => {
    resetData();
    loadData();
  }
);
</script>

<style scoped>
.study-home-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

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

.welcome-title {
  font-size: 26px;
  font-weight: 600;
  color: var(--ctms-text-main);
  margin: 0;
}

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

.study-info {
  margin: 6px 0 0;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: var(--ctms-text-secondary);
}

.study-divider {
  opacity: 0.3;
}

.role-tag {
  background-color: #ffffff;
  border-color: var(--ctms-border-color);
  color: var(--ctms-text-regular);
  font-weight: 500;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.home-alert {
  border: 1px solid var(--ctms-border-color);
  border-radius: var(--ctms-radius);
}

.notifications-card {
  border-radius: 16px;
}

.notifications-header {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 12px;
}

.notifications-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--ctms-text-main);
}

.notifications-subtitle {
  font-size: 12px;
  color: var(--ctms-text-secondary);
}

.notification-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.notification-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 14px;
  border-radius: 12px;
  background: var(--ctms-bg-muted);
}

.notification-main {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.notification-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: var(--ctms-text-main);
}

.notification-version {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  background: var(--ctms-primary-light);
  color: var(--ctms-primary);
}

.notification-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: var(--ctms-text-secondary);
}

.notification-summary {
  max-width: 360px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.quick-nav-section {
  margin-top: 8px;
}

.empty-state-container {
  padding-top: 100px;
}

@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
