<template>
  <div class="page">
    <div class="main-content-flat unified-shell">
      <div class="unified-action-bar actions-only-bar">
        <div class="filter-spacer"></div>
        <el-button v-if="isAdmin" type="primary" @click="openCreate">
          {{ TEXT.common.actions.add }}{{ TEXT.modules.adminProjects.projectLabel }}
        </el-button>
      </div>
      <div class="unified-section project-table-section">
        <el-table :data="projects" v-loading="loading" stripe class="project-table" table-layout="fixed">
          <el-table-column prop="name" :label="TEXT.common.fields.projectName" show-overflow-tooltip>
            <template #default="scope">
              <el-link type="primary" @click="goProject(scope.row)" class="font-medium">{{ scope.row.name }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="code" :label="TEXT.common.fields.projectCode" show-overflow-tooltip>
            <template #default="scope">
              <span class="text-gray-500">{{ scope.row.code || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" :label="TEXT.common.fields.status" align="center">
            <template #default="scope">
              <el-tag :type="statusTag(scope.row.status)" effect="plain" round>{{ statusLabel(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="is_locked" label="锁定状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.is_locked" type="warning" effect="plain" round>已锁定</el-tag>
              <el-tag v-else type="success" effect="plain" round>未锁定</el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.common.labels.actions" width="176" align="center">
            <template #default="scope">
              <div class="action-row">
                <el-tooltip v-if="canProject(scope.row, 'project_members', 'read')" :content="TEXT.modules.adminProjects.members" placement="top">
                  <el-button link type="primary" :icon="User" class="action-btn" @click="goMembers(scope.row)" />
                </el-tooltip>
                <el-tooltip v-if="canProject(scope.row, 'project_members', 'write')" content="权限管理" placement="top">
                  <el-button link type="primary" :icon="Key" class="action-btn" @click="goPermissions(scope.row)" />
                </el-tooltip>
                <el-tooltip v-if="canProject(scope.row, 'sites', 'read')" :content="TEXT.modules.adminProjects.sites" placement="top">
                  <el-button link type="primary" :icon="OfficeBuilding" class="action-btn" @click="goSites(scope.row)" />
                </el-tooltip>
                <el-tooltip v-if="canProject(scope.row, 'audit_export', 'read')" :content="TEXT.menu.auditLogs" placement="top">
                  <el-button link type="primary" :icon="Document" class="action-btn" @click="goAuditLogs(scope.row)" />
                </el-tooltip>
                <el-tooltip :content="TEXT.modules.adminProjects.enter" placement="top">
                  <el-button link type="success" :icon="ArrowRight" class="action-btn enter-btn" @click="enterStudy(scope.row)" />
                </el-tooltip>
                <el-tooltip v-if="isAdmin && !scope.row.is_locked" content="锁定项目" placement="top">
                  <el-button
                    link
                    type="info"
                    :icon="Lock"
                    class="action-btn"
                    @click="handleLockToggle(scope.row)"
                  />
                </el-tooltip>
                <el-tooltip v-if="isAdmin" :content="TEXT.common.actions.delete" placement="top">
                  <el-button link type="danger" :icon="Delete" class="action-btn" @click="handleDelete(scope.row)" />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <ProjectForm v-if="formVisible" v-model:visible="formVisible" :project="editingProject" @saved="loadProjects" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { User, OfficeBuilding, ArrowRight, Delete, Lock, Key, Document } from "@element-plus/icons-vue";
import { fetchStudies, deleteStudy, lockStudy } from "../../api/studies";
import { fetchApiEndpointPermissions } from "../../api/projectPermissions";
import type { ApiEndpointPermissionsResponse, Study } from "../../types/api";
import ProjectForm from "./ProjectForm.vue";
import { useStudyStore } from "../../store/study";
import { useAuthStore } from "../../store/auth";
import { isSystemAdmin } from "../../utils/roles";
import { TEXT } from "../../locales";

const projects = ref<Study[]>([]);
const loading = ref(false);
const formVisible = ref(false);
const editingProject = ref<Study | null>(null);
const router = useRouter();
const studyStore = useStudyStore();
const auth = useAuthStore();
const isAdmin = computed(() => isSystemAdmin(auth.user));
const permissionsByProject = ref<Record<string, ApiEndpointPermissionsResponse>>({});

const loadProjects = async () => {
  loading.value = true;
  try {
    const { data } = await fetchStudies();
    const items = (data as any).items || [];
    projects.value = items;
    if (!isAdmin.value) {
      const entries = await Promise.all(
        items.map(async (item: Study) => {
          try {
            const { data: permissions } = await fetchApiEndpointPermissions(item.id);
            return [item.id, permissions] as const;
          } catch {
            return [item.id, null] as const;
          }
        })
      );
      permissionsByProject.value = Object.fromEntries(entries.filter((entry) => entry[1]));
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.modules.adminProjects.loadFailed);
  } finally {
    loading.value = false;
  }
};

const openCreate = () => {
  if (!isAdmin.value) return;
  editingProject.value = null;
  formVisible.value = true;
};

const MODULE_TO_OPERATION: Record<string, Record<string, string>> = {
  project_members: { read: "project_members:read", write: "project_members:update" },
  sites: { read: "sites:read", write: "sites:update" },
  audit_export: { read: "audit_logs:read", write: "audit_logs:read" },
};

const canProject = (row: Study, module: string, action: "read" | "write") => {
  if (isAdmin.value) return true;
  const role = row.role_in_study || "";
  const operationKey = MODULE_TO_OPERATION[module]?.[action];
  if (!operationKey) return false;
  return !!permissionsByProject.value[row.id]?.[role]?.[operationKey]?.allowed;
};

const goMembers = (row: Study) => {
  router.push(`/admin/permissions/project?projectId=${row.id}&sub=members`);
};

const goSites = (row: Study) => {
  router.push(`/admin/projects/${row.id}/sites`);
};

const goPermissions = (row: Study) => {
  router.push(`/admin/permissions/project?projectId=${row.id}`);
};

const goAuditLogs = async (row: Study) => {
  await enterStudy(row, "/admin/audit-logs");
};

const handleDelete = async (study: Study) => {
  if (!isAdmin.value) return;
  try {
    // 第一次确认
    await ElMessageBox.confirm(
      `确定要删除项目\"${study.name}\"吗？该操作将永久删除项目及其所有关联数据（成员、站点等），且不可恢复！`,
      TEXT.common.actions.delete,
      {
        confirmButtonText: "继续",
        cancelButtonText: TEXT.common.actions.cancel,
        type: "error",
        dangerouslyUseHTMLString: false,
      }
    );
    
    // 第二次确认：要求输入项目名称
    const { value } = await ElMessageBox.prompt(
      `请输入项目名称 "${study.name}" 以确认删除`,
      "删除确认",
      {
        confirmButtonText: TEXT.common.actions.confirm,
        cancelButtonText: TEXT.common.actions.cancel,
        inputPattern: new RegExp(`^${study.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`),
        inputErrorMessage: "项目名称不匹配",
        inputPlaceholder: "请输入项目名称",
        type: "error",
      }
    );
    
    if (value !== study.name) {
      ElMessage.warning("项目名称不匹配，已取消删除");
      return;
    }
    
    const isDeletingCurrentStudy = studyStore.currentStudy?.id === study.id;
    await deleteStudy(study.id);
    if (isDeletingCurrentStudy) {
      await studyStore.rehydrateStudyForLastUser({ preferActive: true });
    }
    ElMessage.success("项目已删除");
    await loadProjects();
  } catch (err: any) {
    if (err !== "cancel") {
      const errorMsg = err?.response?.data?.detail || err?.message || "删除项目失败";
      console.error("删除项目错误:", err);
      ElMessage.error(errorMsg);
    }
  }
};

const handleLockToggle = async (study: Study) => {
  if (!isAdmin.value) return;
  // 锁定后不可解锁
  if (study.is_locked) {
    ElMessage.warning("项目已锁定，不可解锁");
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要锁定项目\"${study.name}\"吗？锁定后项目内数据将无法编辑，且不可解锁！`,
      "锁定项目",
      {
        confirmButtonText: TEXT.common.actions.confirm,
        cancelButtonText: TEXT.common.actions.cancel,
        type: "warning",
      }
    );

    const { value } = await ElMessageBox.prompt(TEXT.modules.adminProjects.lockConfirmPrompt, TEXT.modules.adminProjects.lockConfirmTitle, {
      confirmButtonText: TEXT.common.actions.confirm,
      cancelButtonText: TEXT.common.actions.cancel,
      inputPlaceholder: TEXT.modules.adminProjects.lockConfirmPlaceholder,
      inputValidator: (input: string) => input === "确认锁定" || TEXT.modules.adminProjects.lockConfirmMismatch,
      type: "warning",
    });
    if (value !== "确认锁定") {
      ElMessage.warning(TEXT.modules.adminProjects.lockConfirmMismatchWarning);
      return;
    }
    await lockStudy(study.id);
    ElMessage.success("项目已锁定");
    await loadProjects();
  } catch (err) {
    if (err !== "cancel" && err !== "close") {
      const detail = (err as any)?.response?.data?.detail || "锁定项目失败";
      ElMessage.error(detail);
    }
  }
};

const enterStudy = async (row: Study, path = "/project/overview") => {
  studyStore.setCurrentStudy(row);
  await studyStore.loadCurrentStudyPermissions().catch(() => {});
  router.push(path);
};

const goDetail = (row: Study) => {
  router.push(`/admin/projects/${row.id}`);
};

const goProject = (row: Study) => {
  if (isAdmin.value) {
    goDetail(row);
    return;
  }
  enterStudy(row);
};

const statusLabel = (status: string) =>
  TEXT.enums.projectStatus[status as keyof typeof TEXT.enums.projectStatus] || status;

const statusTag = (status: string) =>
  ({
    DRAFT: "info",
    ACTIVE: "success",
    CLOSED: "warning",
  }[status] || "info");

onMounted(() => {
  loadProjects();
});
</script>

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

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

.main-content-flat :deep(.el-card__body) {
  padding: 0;
}

.action-row {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
  white-space: nowrap;
}

.actions-only-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.project-table-section {
  padding: 0;
}

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

.action-btn {
  width: 28px;
  height: 28px;
  min-height: 28px;
  font-size: 16px;
  padding: 0;
  margin: 0;
  border-radius: 4px;
  transition: background-color 0.2s, color 0.2s, transform 0.2s;
}

.action-row :deep(.el-button + .el-button) {
  margin-left: 0;
}

.action-btn:hover {
  transform: translateY(-1px);
  background-color: #f3f4f6;
}

.enter-btn {
  font-size: 16px;
  font-weight: bold;
}
</style>
