<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1 class="page-title">{{ TEXT.modules.startupMeetingAuth.title }}</h1>
        <p class="page-subtitle">{{ TEXT.modules.startupMeetingAuth.subtitle }}</p>
      </div>
    </div>

    <el-card>
      <el-tabs v-model="activeTab">
        <el-tab-pane :label="TEXT.modules.startupMeetingAuth.kickoffTab" name="kickoff">
          <div class="tab-actions">
            <el-button type="primary" @click="goNewKickoff">{{ TEXT.modules.startupMeetingAuth.kickoffNewTitle }}</el-button>
          </div>
          <el-table :data="kickoffItems" v-loading="loadingKickoff" style="width: 100%">
            <el-table-column prop="kickoff_date" :label="TEXT.common.fields.kickoffDate" width="160">
              <template #default="scope">{{ displayDate(scope.row.kickoff_date) }}</template>
            </el-table-column>
            <el-table-column prop="attendees" :label="TEXT.common.fields.attendees" min-width="200">
              <template #default="scope">
                {{ (scope.row.attendees || []).join("、") || TEXT.common.fallback }}
              </template>
            </el-table-column>
            <el-table-column :label="TEXT.common.labels.actions" width="200">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="goKickoffDetail(scope.row.id)">{{ TEXT.common.actions.view }}</el-button>
                <el-button link type="primary" size="small" @click="goKickoffEdit(scope.row.id)">{{ TEXT.common.actions.edit }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <StateEmpty v-if="!loadingKickoff && kickoffItems.length === 0" :description="TEXT.modules.startupMeetingAuth.emptyKickoff" />
        </el-tab-pane>
        <el-tab-pane :label="TEXT.modules.startupMeetingAuth.trainingTab" name="training">
          <div class="tab-actions">
            <el-button type="primary" @click="goNewTraining">{{ TEXT.modules.startupMeetingAuth.trainingNewTitle }}</el-button>
          </div>
          <el-table :data="trainingItems" v-loading="loadingTraining" style="width: 100%">
            <el-table-column prop="name" :label="TEXT.common.fields.name" min-width="140" />
            <el-table-column prop="role" :label="TEXT.common.labels.role" min-width="120" />
            <el-table-column prop="site_name" :label="TEXT.common.fields.site" min-width="140" />
            <el-table-column :label="TEXT.common.fields.trained" width="120">
              <template #default="scope">
                <el-checkbox v-model="scope.row.trained" @change="toggleTraining(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column :label="TEXT.common.fields.authorized" width="120">
              <template #default="scope">
                <el-checkbox v-model="scope.row.authorized" @change="toggleTraining(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column :label="TEXT.common.labels.actions" width="200">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="goTrainingDetail(scope.row.id)">{{ TEXT.common.actions.view }}</el-button>
                <el-button link type="primary" size="small" @click="goTrainingEdit(scope.row.id)">{{ TEXT.common.actions.edit }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <StateEmpty v-if="!loadingTraining && trainingItems.length === 0" :description="TEXT.modules.startupMeetingAuth.emptyTraining" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useStudyStore } from "../../store/study";
import { listKickoffs, listTrainingAuthorizations, updateTrainingAuthorization } from "../../api/startup";
import { displayDate } from "../../utils/display";
import StateEmpty from "../../components/StateEmpty.vue";
import { TEXT } from "../../locales";

const router = useRouter();
const study = useStudyStore();
const activeTab = ref("kickoff");
const kickoffItems = ref<any[]>([]);
const trainingItems = ref<any[]>([]);
const loadingKickoff = ref(false);
const loadingTraining = ref(false);

const loadKickoffs = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  loadingKickoff.value = true;
  try {
    const { data } = await listKickoffs(studyId);
    kickoffItems.value = Array.isArray(data) ? data : data.items || [];
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  } finally {
    loadingKickoff.value = false;
  }
};

const loadTraining = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  loadingTraining.value = true;
  try {
    const { data } = await listTrainingAuthorizations(studyId);
    trainingItems.value = Array.isArray(data) ? data : data.items || [];
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  } finally {
    loadingTraining.value = false;
  }
};

const toggleTraining = async (row: any) => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  try {
    await updateTrainingAuthorization(studyId, row.id, {
      trained: row.trained,
      authorized: row.authorized,
    });
    ElMessage.success(TEXT.common.messages.saveSuccess);
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.saveFailed);
    loadTraining();
  }
};

const goNewKickoff = () => router.push("/startup/kickoff/new");
const goKickoffDetail = (id: string) => router.push(`/startup/kickoff/${id}`);
const goKickoffEdit = (id: string) => router.push(`/startup/kickoff/${id}/edit`);

const goNewTraining = () => router.push("/startup/training/new");
const goTrainingDetail = (id: string) => router.push(`/startup/training/${id}`);
const goTrainingEdit = (id: string) => router.push(`/startup/training/${id}/edit`);

onMounted(() => {
  loadKickoffs();
  loadTraining();
});
</script>

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

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
}

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

.tab-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
