<template>
  <div class="page">
    <div class="unified-shell">
      <section class="unified-section">
        <div class="unified-section-header">
          <div class="ctms-section-title">{{ isEdit ? TEXT.modules.startupFeasibilityEthics.feasibilityEditTitle : TEXT.modules.startupFeasibilityEthics.feasibilityNewTitle }}</div>
          <div class="ctms-section-actions">
            <el-button @click="goBack">
              <el-icon class="el-icon--left"><ArrowLeft /></el-icon>
              {{ TEXT.common.actions.back }}
            </el-button>
          </div>
        </div>
        <el-form :model="form" label-width="140px" class="ctms-form" label-position="top">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item :label="TEXT.common.fields.site">
                <el-select v-model="form.site_id" :disabled="isReadOnly" :placeholder="TEXT.common.placeholders.select" clearable style="width: 100%">
                  <el-option v-for="site in siteOptions" :key="site.value" :label="site.label" :value="site.value" :disabled="site.disabled" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="TEXT.common.fields.projectNo">
                <el-input v-model="form.project_no" :disabled="isReadOnly" :placeholder="TEXT.common.placeholders.input + TEXT.common.fields.projectNo" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item :label="TEXT.common.fields.submitDate">
                <el-date-picker
                  v-model="form.submit_date"
                  :disabled="isReadOnly"
                  type="date"
                  value-format="YYYY-MM-DD"
                  :placeholder="TEXT.common.placeholders.select"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="TEXT.common.fields.acceptDate">
                <el-date-picker
                  v-model="form.accept_date"
                  :disabled="isReadOnly"
                  type="date"
                  value-format="YYYY-MM-DD"
                  :placeholder="TEXT.common.placeholders.select"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="TEXT.common.fields.approvedDate">
                <el-date-picker
                  v-model="form.approved_date"
                  :disabled="isReadOnly"
                  type="date"
                  value-format="YYYY-MM-DD"
                  :placeholder="TEXT.common.placeholders.select"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item class="form-actions">
            <el-button type="primary" :loading="saving" :disabled="isReadOnly" @click="submit">{{ TEXT.common.actions.save }}</el-button>
            <el-button @click="goBack">{{ TEXT.common.actions.cancel }}</el-button>
          </el-form-item>
        </el-form>
      </section>
      <section class="unified-section">
        <template v-if="isEdit && recordId">
          <div class="ctms-section-header">
            <div class="ctms-section-title">{{ TEXT.common.labels.attachments }}</div>
          </div>
          <AttachmentList
            :study-id="studyId"
            entity-type="startup_feasibility"
            :entity-id="recordId"
            :readonly="isReadOnly"
          />
        </template>
        <StateEmpty v-else :description="TEXT.modules.startupFeasibilityEthics.feasibilityUploadHint" />
      </section>
    </div>
  </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 { ArrowLeft } from "@element-plus/icons-vue";
import { useStudyStore } from "../../store/study";
import { createFeasibility, getFeasibility, updateFeasibility } from "../../api/startup";
import { fetchSites } from "../../api/sites";
import type { Site } from "../../types/api";
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 recordId = computed(() => route.params.recordId as string | undefined);
const isEdit = computed(() => !!recordId.value);
const studyId = computed(() => study.currentStudy?.id || "");
const sites = ref<Site[]>([]);

const siteOptions = computed(() =>
  sites.value.map((site) => ({ value: site.id, label: site.name || TEXT.common.fallback, disabled: !site.is_active }))
);
const siteActiveMap = computed(() => {
  const map: Record<string, boolean> = {};
  sites.value.forEach((site) => {
    if (site?.id) map[site.id] = !!site.is_active;
  });
  return map;
});
const isReadOnly = computed(() => isEdit.value && !!form.site_id && siteActiveMap.value[form.site_id] === false);

const form = reactive({
  site_id: "",
  submit_date: "",
  accept_date: "",
  approved_date: "",
  project_no: "",
});

const loadSites = async () => {
  if (!studyId.value) return;
  try {
    const { data } = await fetchSites(studyId.value, { limit: 500 });
    sites.value = Array.isArray(data) ? data : data.items || [];
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  }
};

const load = async () => {
  if (!isEdit.value || !studyId.value || !recordId.value) return;
  try {
    const { data } = await getFeasibility(studyId.value, recordId.value);
    Object.assign(form, {
      site_id: data.site_id || "",
      submit_date: data.submit_date || "",
      accept_date: data.accept_date || "",
      approved_date: data.approved_date || "",
      project_no: data.project_no || "",
    });
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  }
};

const submit = async () => {
  if (!studyId.value) return;
  if (isReadOnly.value) {
    ElMessage.warning("中心已停用");
    return;
  }
  if (form.site_id && siteActiveMap.value[form.site_id] === false) {
    ElMessage.warning("中心已停用");
    return;
  }
  saving.value = true;
  try {
    const payload = {
      site_id: form.site_id || null,
      submit_date: form.submit_date || null,
      accept_date: form.accept_date || null,
      approved_date: form.approved_date || null,
      project_no: form.project_no || null,
    };
    if (isEdit.value && recordId.value) {
      await updateFeasibility(studyId.value, recordId.value, payload);
      ElMessage.success(TEXT.common.messages.saveSuccess);
      router.push(`/startup/feasibility/${recordId.value}`);
    } else {
      const { data } = await createFeasibility(studyId.value, payload);
      ElMessage.success(TEXT.common.messages.createSuccess);
      router.push(`/startup/feasibility/${data.id}`);
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.saveFailed);
  } finally {
    saving.value = false;
  }
};

const goBack = () => router.push("/startup/feasibility-ethics");

onMounted(() => {
  loadSites();
  load();
});
</script>

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

.form-actions {
  margin-top: 24px;
}
</style>
