<template>
  <div class="page page--flush">

    <div class="main-content-flat unified-shell">
      <div class="filter-container unified-action-bar">
        <el-form :inline="true" :model="filters" class="filter-form">
          <div class="filter-item">
            <el-select v-model="filters.center_id" clearable :placeholder="TEXT.common.fields.site" class="filter-select">
              <template #prefix>
                <el-icon><Location /></el-icon>
              </template>
              <el-option
                v-for="site in sites"
                :key="site.id"
                :label="site.name || TEXT.common.fallback"
                :value="site.id"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="filters.direction" clearable :placeholder="TEXT.common.fields.direction" class="filter-select">
              <template #prefix>
                <el-icon><Menu /></el-icon>
              </template>
              <el-option :label="TEXT.enums.shipmentDirection.SEND" value="SEND" />
              <el-option :label="TEXT.enums.shipmentDirection.RETURN" value="RETURN" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="filters.status" clearable :placeholder="TEXT.common.fields.status" class="filter-select">
              <template #prefix>
                <el-icon><CircleCheck /></el-icon>
              </template>
              <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>
          </div>
          <div class="filter-actions">
            <el-button @click="resetFilters">{{ TEXT.common.actions.reset }}</el-button>
          </div>
          <div class="filter-spacer"></div>
          <el-button type="primary" @click="goNew">
            <el-icon class="el-icon--left"><Plus /></el-icon>
            {{ TEXT.modules.drugShipments.newTitle }}
          </el-button>
        </el-form>
      </div>
      <div class="unified-section table-section section--flush-x section--flush-top section--flush-bottom">
        <el-table
          :data="sortedItems"
          v-loading="loading"
          style="width: 100%"
          class="shipment-table"
          :row-class-name="shipmentRowClass"
          @row-click="onRowClick"
          table-layout="fixed"
        >
          <el-table-column prop="site_name" :label="TEXT.common.fields.site" width="150" show-overflow-tooltip>
            <template #default="scope">{{ scope.row.site_name || TEXT.common.fallback }}</template>
          </el-table-column>
          <el-table-column prop="direction" :label="TEXT.common.fields.direction" width="120">
            <template #default="scope">
              <el-tag :class="['type-tag', scope.row.direction === 'SEND' ? 'type-send' : 'type-return']" effect="light">
                {{ displayEnum(TEXT.enums.shipmentDirection, scope.row.direction) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ship_date" :label="TEXT.common.fields.shipDate" width="165">
            <template #default="scope">{{ displayDate(scope.row.ship_date) }}</template>
          </el-table-column>
          <el-table-column prop="receive_date" :label="TEXT.common.fields.receiveDate" width="145">
            <template #default="scope">{{ displayDate(scope.row.receive_date) }}</template>
          </el-table-column>
          <el-table-column prop="quantity" :label="TEXT.common.fields.quantity" width="100" align="right">
            <template #default="scope">{{ typeof scope.row.quantity === "number" ? scope.row.quantity : TEXT.common.fallback }}</template>
          </el-table-column>
          <el-table-column prop="batch_no" :label="TEXT.common.fields.batchNo" width="120" show-overflow-tooltip>
            <template #default="scope">{{ scope.row.batch_no || TEXT.common.fallback }}</template>
          </el-table-column>
          <el-table-column prop="status" :label="TEXT.common.fields.status" width="120">
            <template #default="scope">
              <el-tag :type="statusType(scope.row.status)" effect="plain" round size="small" class="status-tag">
                {{ displayEnum(TEXT.enums.shipmentStatus, scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" :label="TEXT.common.fields.remark" width="160" show-overflow-tooltip>
            <template #default="scope">{{ scope.row.remark || TEXT.common.fallback }}</template>
          </el-table-column>
          <el-table-column :label="TEXT.common.labels.actions" width="110" align="center">
            <template #default="scope">
              <el-button
                link
                type="danger"
                size="small"
                :disabled="isInactiveSite(scope.row.center_id)"
                @click.stop="remove(scope.row)"
              >
                {{ TEXT.common.actions.delete }}
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <div v-if="!loading" class="table-empty">{{ TEXT.modules.drugShipments.empty }}</div>
          </template>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Location, Menu, CircleCheck, Plus } from "@element-plus/icons-vue";
import { useStudyStore } from "../../store/study";
import { listDrugShipments, deleteDrugShipment } from "../../api/drugShipments";
import { fetchSites } from "../../api/sites";
import { displayDate, displayEnum } from "../../utils/display";
import { TEXT } from "../../locales";

const router = useRouter();
const study = useStudyStore();
const loading = ref(false);
const items = ref<any[]>([]);
const sites = ref<any[]>([]);
const siteActiveMap = ref<Record<string, boolean>>({});
const filters = reactive({
  center_id: study.currentSite?.id || "",
  direction: "",
  status: "",
});

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 || [];
    siteActiveMap.value = sites.value.reduce((acc: Record<string, boolean>, site: any) => {
      acc[site.id] = !!site.is_active;
      return acc;
    }, {});
  } catch {
    sites.value = [];
    siteActiveMap.value = {};
  }
};

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

const resetFilters = () => {
  filters.center_id = "";
  filters.direction = "";
  filters.status = "";
};

const goNew = () => router.push("/drug/shipments/new");
const goDetail = (id: string) => router.push(`/drug/shipments/${id}`);
const onRowClick = (row: any) => {
  if (!row?.id) return;
  goDetail(row.id);
};
const isInactiveSite = (siteId?: string) => !!siteId && siteActiveMap.value[siteId] === false;
const shipmentRowClass = ({ row }: { row: any }) =>
  `${row?.id ? "clickable-row" : ""}${isInactiveSite(row?.center_id) ? " row-inactive" : ""}`.trim();
const filteredItems = computed(() =>
  items.value.filter((item) => {
    if (filters.center_id && item?.center_id !== filters.center_id) return false;
    if (filters.direction && item?.direction !== filters.direction) return false;
    if (filters.status && item?.status !== filters.status) return false;
    return true;
  })
);
const sortedItems = computed(() =>
  [...filteredItems.value].sort((a, b) => Number(isInactiveSite(a?.center_id)) - Number(isInactiveSite(b?.center_id)))
);

const statusType = (status: string) => {
  switch (status) {
    case "PENDING":
      return "info";
    case "IN_TRANSIT":
      return "primary";
    case "SIGNED":
      return "success";
    case "RETURNED":
      return "warning";
    case "EXCEPTION":
      return "danger";
    default:
      return "info";
  }
};

const remove = async (row: any) => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  if (isInactiveSite(row?.center_id)) {
    ElMessage.warning("中心已停用");
    return;
  }
  const ok = await ElMessageBox.confirm(TEXT.modules.drugShipments.confirmDelete, TEXT.common.labels.tips).catch(() => null);
  if (!ok) return;
  try {
    await deleteDrugShipment(studyId, row.id);
    ElMessage.success(TEXT.common.messages.deleteSuccess);
    load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.deleteFailed);
  }
};

watch(() => filters.center_id, (val: string) => {
  if (val) {
    const matched = sites.value.find(s => s.id === val);
    if (matched) study.setCurrentSite(matched);
  } else {
    study.setCurrentSite(null);
  }
});

watch(() => study.currentSite, (newSite: any) => {
  filters.center_id = newSite?.id || "";
});

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

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

.filter-form {
  display: flex;
  width: 100%;
  gap: 8px;
  align-items: center;
}

.filter-item {
  margin-bottom: 0 !important;
  margin-right: 0 !important;
}

.filter-actions {
  margin-bottom: 0 !important;
  margin-right: 0 !important;
}

.filter-actions :deep(.el-form-item__content) {
  align-items: center;
}

.filter-actions :deep(.el-button) {
  height: 32px;
  line-height: 32px;
  padding: 0 12px;
  border-radius: 10px;
}

.filter-select {
  width: 140px;
}

.filter-spacer {
  flex: 1;
}

.shipment-table :deep(.el-table__inner-wrapper::before) {
  display: none;
}

.type-tag {
  font-weight: 600;
  border: none;
}

.type-send {
  background-color: #fff7ed !important;
  color: #ea580c !important;
}

.type-return {
  background-color: #fefce8 !important;
  color: #ca8a04 !important;
}

.status-tag {
  font-weight: 500;
}

.text-muted {
  color: var(--ctms-text-placeholder);
}
.table-empty {
  min-height: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8a97ab;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 0.02em;
}
</style>

<style>
.row-inactive td {
  color: var(--ctms-text-secondary);
  background-color: #fff7d6 !important;
}

.row-inactive .el-tag {
  opacity: 0.6;
}
</style>
