<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1 class="page-title">{{ isEdit ? TEXT.modules.startupMeetingAuth.kickoffEditTitle : TEXT.modules.startupMeetingAuth.kickoffNewTitle }}</h1>
        <p class="page-subtitle">{{ TEXT.modules.startupMeetingAuth.kickoffFormSubtitle }}</p>
      </div>
      <el-button @click="goBack">{{ TEXT.common.actions.back }}</el-button>
    </div>

    <el-card>
      <el-form :model="form" label-width="120px">
        <el-form-item :label="TEXT.common.fields.kickoffDate">
          <el-date-picker v-model="form.kickoff_date" type="date" value-format="YYYY-MM-DD" :placeholder="TEXT.common.placeholders.select" />
        </el-form-item>
        <el-form-item :label="TEXT.common.fields.attendees">
          <el-input
            v-model="form.attendees"
            type="textarea"
            :rows="4"
            :placeholder="TEXT.modules.startupMeetingAuth.attendeesPlaceholder"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="saving" @click="submit">{{ TEXT.common.actions.save }}</el-button>
          <el-button @click="goBack">{{ TEXT.common.actions.cancel }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <AttachmentList
      v-if="isEdit && meetingId"
      :study-id="studyId"
      entity-type="startup_kickoff"
      :entity-id="meetingId"
    />
    <el-card v-else class="hint-card">
      <StateEmpty :description="TEXT.modules.startupMeetingAuth.kickoffUploadHint" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useStudyStore } from "../../store/study";
import { createKickoff, getKickoff, updateKickoff } from "../../api/startup";
import AttachmentList from "../../components/attachments/AttachmentList.vue";
import StateEmpty from "../../components/StateEmpty.vue";
import { TEXT } from "../../locales";

const route = useRoute();
const router = useRouter();
const study = useStudyStore();
const saving = ref(false);

const meetingId = computed(() => route.params.meetingId as string | undefined);
const isEdit = computed(() => !!meetingId.value);
const studyId = computed(() => study.currentStudy?.id || "");

const form = reactive({
  kickoff_date: "",
  attendees: "",
});

const parseAttendees = (value: string) => {
  return value
    .split("\n")
    .map((item) => item.trim())
    .filter(Boolean);
};

const load = async () => {
  if (!isEdit.value || !studyId.value || !meetingId.value) return;
  try {
    const { data } = await getKickoff(studyId.value, meetingId.value);
    Object.assign(form, {
      kickoff_date: data.kickoff_date || "",
      attendees: Array.isArray(data.attendees) ? data.attendees.join("\n") : "",
    });
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  }
};

const submit = async () => {
  if (!studyId.value) return;
  saving.value = true;
  try {
    const payload = {
      kickoff_date: form.kickoff_date || null,
      attendees: parseAttendees(form.attendees),
    };
    if (isEdit.value && meetingId.value) {
      await updateKickoff(studyId.value, meetingId.value, payload);
      ElMessage.success(TEXT.common.messages.saveSuccess);
      router.push(`/startup/kickoff/${meetingId.value}`);
    } else {
      const { data } = await createKickoff(studyId.value, payload);
      ElMessage.success(TEXT.common.messages.createSuccess);
      router.push(`/startup/kickoff/${data.id}`);
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.saveFailed);
  } finally {
    saving.value = false;
  }
};

const goBack = () => router.push("/startup/meeting-auth");

onMounted(load);
</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);
}

.hint-card {
  padding: 12px;
}
</style>
