<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1 class="page-title">{{ isEdit ? TEXT.modules.subjectForm.titleEdit : TEXT.modules.subjectForm.titleNew }}</h1>
        <p class="page-subtitle">{{ TEXT.modules.subjectForm.subtitle }}</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.subjectNo" required>
          <el-input v-model="form.subject_no" :disabled="isEdit" :placeholder="TEXT.common.placeholders.input + TEXT.common.fields.subjectNo" />
        </el-form-item>
        <el-form-item :label="TEXT.common.fields.site" required>
          <el-select v-model="form.site_id" :disabled="isEdit" :placeholder="TEXT.common.placeholders.select">
            <el-option v-for="site in sites" :key="site.id" :label="site.name" :value="site.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="TEXT.common.fields.screeningDate">
          <el-date-picker
            v-model="form.screening_date"
            type="date"
            value-format="YYYY-MM-DD"
            :placeholder="TEXT.common.placeholders.select"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item v-if="isEdit" :label="TEXT.common.fields.status">
          <el-select v-model="form.status" :placeholder="TEXT.common.placeholders.select">
            <el-option :label="TEXT.enums.subjectStatus.SCREENING" value="SCREENING" />
            <el-option :label="TEXT.enums.subjectStatus.ENROLLED" value="ENROLLED" />
            <el-option :label="TEXT.enums.subjectStatus.COMPLETED" value="COMPLETED" />
            <el-option :label="TEXT.enums.subjectStatus.DROPPED" value="DROPPED" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isEdit" :label="TEXT.common.fields.enrollmentDate">
          <el-date-picker v-model="form.enrollment_date" type="date" value-format="YYYY-MM-DD" :placeholder="TEXT.common.placeholders.select" />
        </el-form-item>
        <el-form-item v-if="isEdit" :label="TEXT.common.fields.completionDate">
          <el-date-picker v-model="form.completion_date" type="date" value-format="YYYY-MM-DD" :placeholder="TEXT.common.placeholders.select" />
        </el-form-item>
        <el-form-item v-if="isEdit" :label="TEXT.common.fields.dropReason">
          <el-input v-model="form.drop_reason" type="textarea" :rows="3" :placeholder="TEXT.common.placeholders.input" />
        </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>
  </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 { createSubject, getSubject, updateSubject } from "../../api/subjects";
import { fetchSites } from "../../api/sites";
import { TEXT } from "../../locales";

const route = useRoute();
const router = useRouter();
const study = useStudyStore();
const saving = ref(false);
const sites = ref<any[]>([]);

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

const form = reactive({
  subject_no: "",
  site_id: "",
  screening_date: "",
  status: "SCREENING",
  enrollment_date: "",
  completion_date: "",
  drop_reason: "",
});

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 {
    sites.value = [];
  }
};

const load = async () => {
  if (!isEdit.value || !studyId.value || !subjectId.value) return;
  try {
    const { data } = await getSubject(studyId.value, subjectId.value);
    Object.assign(form, {
      subject_no: data.subject_no || "",
      site_id: data.site_id || "",
      screening_date: data.screening_date || "",
      status: data.status || "SCREENING",
      enrollment_date: data.enrollment_date || "",
      completion_date: data.completion_date || "",
      drop_reason: data.drop_reason || "",
    });
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  }
};

const submit = async () => {
  if (!studyId.value) return;
  saving.value = true;
  try {
    if (isEdit.value && subjectId.value) {
      const payload = {
        status: form.status || null,
        enrollment_date: form.enrollment_date || null,
        completion_date: form.completion_date || null,
        drop_reason: form.drop_reason || null,
      };
      await updateSubject(studyId.value, subjectId.value, payload);
      ElMessage.success(TEXT.common.messages.saveSuccess);
      router.push(`/subjects/${subjectId.value}`);
    } else {
      const payload = {
        subject_no: form.subject_no,
        site_id: form.site_id,
        screening_date: form.screening_date || null,
      };
      const { data } = await createSubject(studyId.value, payload);
      ElMessage.success(TEXT.common.messages.createSuccess);
      router.push(`/subjects/${data.id}`);
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.saveFailed);
  } finally {
    saving.value = false;
  }
};

const goBack = () => router.push("/subjects");

onMounted(async () => {
  await loadSites();
  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);
}
</style>
