<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1 class="page-title">{{ isEdit ? TEXT.modules.drugShipments.editTitle : TEXT.modules.drugShipments.newTitle }}</h1>
        <p class="page-subtitle">{{ TEXT.modules.drugShipments.formSubtitle }}</p>
      </div>
      <el-button @click="goBack">{{ TEXT.common.actions.back }}</el-button>
    </div>

    <el-card>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="top">
        <h3 class="section-title">{{ TEXT.common.labels.basicInfo }}</h3>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item :label="TEXT.common.fields.site" prop="center_id">
              <el-select v-model="form.center_id" :placeholder="TEXT.common.placeholders.select" style="width: 100%" :disabled="isReadOnly">
                <el-option
                  v-for="site in sites"
                  :key="site.id"
                  :label="site.name || TEXT.common.fallback"
                  :value="site.id"
                  :disabled="!site.is_active"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="TEXT.common.fields.direction" prop="direction">
              <el-select v-model="form.direction" :placeholder="TEXT.common.placeholders.select" style="width: 100%" :disabled="isReadOnly">
                <el-option :label="TEXT.enums.shipmentDirection.SEND" value="SEND" />
                <el-option :label="TEXT.enums.shipmentDirection.RETURN" value="RETURN" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="TEXT.common.fields.status" prop="status">
              <el-select v-model="form.status" :placeholder="TEXT.common.placeholders.select" style="width: 100%" :disabled="isReadOnly">
                <el-option :label="TEXT.enums.shipmentStatus.PENDING" value="PENDING" />
                <el-option :label="TEXT.enums.shipmentStatus.IN_TRANSIT" value="IN_TRANSIT" />
                <el-option :label="TEXT.enums.shipmentStatus.SIGNED" value="SIGNED" />
                <el-option :label="TEXT.enums.shipmentStatus.RETURNED" value="RETURNED" />
                <el-option :label="TEXT.enums.shipmentStatus.EXCEPTION" value="EXCEPTION" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <h3 class="section-title">{{ TEXT.modules.drugShipments.recordLabel }}</h3>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item :label="TEXT.common.fields.shipDate" prop="ship_date">
              <el-date-picker v-model="form.ship_date" type="date" value-format="YYYY-MM-DD" :placeholder="TEXT.common.placeholders.select" style="width: 100%" :disabled="isReadOnly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="TEXT.common.fields.receiveDate" prop="receive_date">
              <el-date-picker v-model="form.receive_date" type="date" value-format="YYYY-MM-DD" :placeholder="TEXT.common.placeholders.select" style="width: 100%" :disabled="isReadOnly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="TEXT.common.fields.quantity" prop="quantity">
              <el-input-number v-model="form.quantity" :min="0" :controls="false" :placeholder="TEXT.common.placeholders.input" style="width: 100%" :disabled="isReadOnly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="TEXT.common.fields.batchNo" prop="batch_no">
              <el-input v-model="form.batch_no" :placeholder="TEXT.common.placeholders.input + TEXT.common.fields.batchNo" :disabled="isReadOnly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="TEXT.common.fields.carrier" prop="carrier">
              <el-input v-model="form.carrier" :placeholder="TEXT.common.placeholders.input + TEXT.common.fields.carrier" :disabled="isReadOnly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="TEXT.common.fields.trackingNo" prop="tracking_no">
              <el-input v-model="form.tracking_no" :placeholder="TEXT.common.placeholders.input + TEXT.common.fields.trackingNo" :disabled="isReadOnly" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item :label="TEXT.common.fields.remark" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" :placeholder="TEXT.common.placeholders.input" :disabled="isReadOnly" />
        </el-form-item>

        <el-form-item>
          <div class="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>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <AttachmentList
      v-if="isEdit && shipmentId"
      :study-id="studyId"
      entity-type="drug_shipment"
      :entity-id="shipmentId"
    />
    <el-card v-else class="hint-card">
      <StateEmpty :description="TEXT.modules.drugShipments.uploadHint" />
    </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 { createDrugShipment, getDrugShipment, updateDrugShipment } from "../../api/drugShipments";
import { fetchSites } from "../../api/sites";
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 formRef = ref();
const sites = ref<any[]>([]);
const siteActiveMap = computed(() => {
  const map: Record<string, boolean> = {};
  sites.value.forEach((site) => {
    if (site?.id) map[site.id] = !!site.is_active;
  });
  return map;
});

const shipmentId = computed(() => route.params.shipmentId as string | undefined);
const isEdit = computed(() => !!shipmentId.value);
const studyId = computed(() => study.currentStudy?.id || "");
const isReadOnly = computed(() => isEdit.value && !!form.center_id && siteActiveMap.value[form.center_id] === false);

const form = reactive({
  center_id: "",
  direction: "SEND",
  ship_date: "",
  receive_date: "",
  quantity: null as number | null,
  batch_no: "",
  carrier: "",
  tracking_no: "",
  status: "PENDING",
  remark: "",
});

const rules = {
  center_id: [{ required: true, message: TEXT.common.messages.required, trigger: "change" }],
  direction: [{ required: true, message: TEXT.common.messages.required, trigger: "change" }],
  ship_date: [{ required: true, message: TEXT.common.messages.required, trigger: "change" }],
  receive_date: [{ required: true, message: TEXT.common.messages.required, trigger: "change" }],
  quantity: [{ required: true, type: "number", message: TEXT.common.messages.required, trigger: "change" }],
  batch_no: [{ required: true, message: TEXT.common.messages.required, trigger: "blur" }],
  carrier: [{ required: true, message: TEXT.common.messages.required, trigger: "blur" }],
  tracking_no: [{ required: true, message: TEXT.common.messages.required, trigger: "blur" }],
  status: [{ required: true, message: TEXT.common.messages.required, trigger: "change" }],
  remark: [{ required: true, message: TEXT.common.messages.required, trigger: "blur" }],
};

const loadSites = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  try {
    const { data } = await fetchSites(studyId, { limit: 500 });
    sites.value = Array.isArray(data) ? data : data.items || [];
  } catch {
    sites.value = [];
  }
};

const load = async () => {
  if (!isEdit.value || !studyId.value || !shipmentId.value) return;
  try {
    const { data } = await getDrugShipment(studyId.value, shipmentId.value);
    Object.assign(form, {
      direction: data.direction || "SEND",
      center_id: data.center_id || "",
      ship_date: data.ship_date || "",
      receive_date: data.receive_date || "",
      quantity: data.quantity ?? null,
      batch_no: data.batch_no || "",
      carrier: data.carrier || "",
      tracking_no: data.tracking_no || "",
      status: data.status || "PENDING",
      remark: data.remark || "",
    });
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  }
};

const submit = async () => {
  if (isReadOnly.value) {
    ElMessage.warning("中心已停用");
    return;
  }
  if (!studyId.value) return;
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;
  saving.value = true;
  try {
    const payload = {
      center_id: form.center_id,
      direction: form.direction,
      ship_date: form.ship_date || null,
      receive_date: form.receive_date || null,
      quantity: form.quantity,
      batch_no: form.batch_no,
      carrier: form.carrier || null,
      tracking_no: form.tracking_no || null,
      status: form.status,
      remark: form.remark || null,
    };
    if (isEdit.value && shipmentId.value) {
      await updateDrugShipment(studyId.value, shipmentId.value, payload);
      ElMessage.success(TEXT.common.messages.saveSuccess);
      router.push(`/drug/shipments/${shipmentId.value}`);
    } else {
      const { data } = await createDrugShipment(studyId.value, payload);
      ElMessage.success(TEXT.common.messages.createSuccess);
      router.push(`/drug/shipments/${data.id}`);
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.saveFailed);
  } finally {
    saving.value = false;
  }
};

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

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);
}

.hint-card {
  padding: 12px;
}

.section-title {
  margin: 0 0 24px;
  font-size: 16px;
  font-weight: 600;
  color: var(--ctms-text-primary);
  border-left: 4px solid var(--ctms-primary);
  padding-left: 12px;
}

.actions {
  display: flex;
  gap: 12px;
}
</style>
