<template>
  <el-card>
    <div class="header">
      <span>{{ TEXT.common.labels.attachments }}</span>
      <AttachmentUploader
        :study-id="studyId"
        :entity-type="entityType"
        :entity-id="entityId"
        @uploaded="load"
      />
    </div>
    <el-table :data="attachments" v-loading="loading" style="width: 100%">
      <el-table-column prop="filename" :label="TEXT.common.labels.filename" min-width="200" />
      <el-table-column :label="TEXT.common.labels.size" width="120">
        <template #default="scope">{{ formatFileSize(scope.row.file_size ?? scope.row.size) }}</template>
      </el-table-column>
      <el-table-column :label="TEXT.common.labels.uploader" width="180">
        <template #default="scope">
          {{ uploaderLabel(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="uploaded_at" :label="TEXT.common.labels.uploadedAt" width="180">
        <template #default="scope">
          {{ displayDateTime(scope.row.uploaded_at) }}
        </template>
      </el-table-column>
      <el-table-column :label="TEXT.common.labels.actions" width="220">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="preview(scope.row)">
            {{ TEXT.common.actions.view }}
          </el-button>
          <el-button link type="primary" size="small" @click="download(scope.row)">{{ TEXT.common.actions.download }}</el-button>
          <el-button
            v-if="canDelete(scope.row)"
            link
            type="danger"
            size="small"
            @click="remove(scope.row)"
          >
            {{ TEXT.common.actions.delete }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <el-dialog v-model="previewVisible" :title="previewTitle" width="720px" :close-on-click-modal="false">
    <div v-if="previewError" class="preview-error">
      {{ previewError }}
    </div>
    <template v-else>
      <img v-if="previewType === 'image'" :src="previewUrl" class="preview-media" />
      <iframe v-else-if="previewType === 'pdf'" :src="previewUrl" class="preview-frame" />
      <div v-else class="preview-error">
        {{ TEXT.common.messages.previewNotSupported }}
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { fetchAttachments, deleteAttachment } from "../../api/attachments";
import AttachmentUploader from "./AttachmentUploader.vue";
import { formatFileSize } from "./attachmentUtils";
import { useAuthStore } from "../../store/auth";
import { useStudyStore } from "../../store/study";
import { listMembers } from "../../api/members";
import { displayDateTime, displayUser, getMemberDisplayName, getUserDisplayName } from "../../utils/display";
import { TEXT } from "../../locales";

const props = defineProps<{
  studyId: string;
  entityType: string;
  entityId: string;
}>();

const attachments = ref<any[]>([]);
const loading = ref(false);
const auth = useAuthStore();
const study = useStudyStore();
const members = ref<any[]>([]);
const previewVisible = ref(false);
const previewUrl = ref("");
const previewType = ref<"image" | "pdf" | "other">("other");
const previewTitle = ref(TEXT.common.labels.preview);
const previewError = ref("");

const load = async () => {
  if (!props.studyId || !props.entityId) return;
  loading.value = true;
  try {
    const { data } = await fetchAttachments(props.studyId, props.entityType, props.entityId);
    attachments.value = data.items || data || [];
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  } finally {
    loading.value = false;
  }
};

const loadMembers = async () => {
  if (!props.studyId) return;
  try {
    const { data } = await listMembers(props.studyId, { limit: 500 });
    members.value = Array.isArray(data) ? data : data.items || [];
  } catch {
    members.value = [];
  }
};

const uploaderLabel = (row: any) => {
  const memberMap = members.value.reduce<Record<string, string>>((acc, cur) => {
    const username = getMemberDisplayName(cur);
    if (cur?.user_id && username) acc[cur.user_id] = username;
    return acc;
  }, {});
  if (row?.uploaded_by && typeof row.uploaded_by === "object") {
    return getUserDisplayName(row.uploaded_by) || row.uploaded_by.id || TEXT.common.fallback;
  }
  return displayUser(row.uploaded_by_id || row.uploaded_by, { members: memberMap });
};

const download = (row: any) => {
  const token = localStorage.getItem("ctms_token");
  const url = token ? `/api/v1/attachments/${row.id}/download?token=${token}` : `/api/v1/attachments/${row.id}/download`;
  window.open(url, "_blank");
};

const detectPreviewType = (row: any) => {
  const mime = (row?.mime_type || row?.content_type || "").toLowerCase();
  if (mime.startsWith("image/")) return "image";
  if (mime === "application/pdf") return "pdf";
  return "other";
};

const preview = (row: any) => {
  previewError.value = "";
  previewType.value = detectPreviewType(row);
  previewTitle.value = row?.filename || TEXT.common.labels.preview;
  const token = localStorage.getItem("ctms_token");
  previewUrl.value = row?.url || (token ? `/api/v1/attachments/${row.id}/download?token=${token}` : `/api/v1/attachments/${row.id}/download`);
  if (previewType.value === "other") {
    previewError.value = TEXT.common.messages.previewNotSupported;
  }
  previewVisible.value = true;
};

const canDelete = (row: any) => {
  const userId = auth.user?.id;
  const role = auth.user?.role;
  const projectRole = study.currentStudyRole || (study.currentStudy as any)?.role_in_study;
  const ownerId =
    row.uploaded_by_id || (row.uploaded_by && typeof row.uploaded_by === "object" ? row.uploaded_by.id : row.uploaded_by);
  return userId === ownerId || role === "ADMIN" || projectRole === "PM";
};

const remove = async (row: any) => {
  const ok = await ElMessageBox.confirm(TEXT.common.confirm.delete, TEXT.common.labels.tips).catch(() => null);
  if (!ok) return;
  try {
    await deleteAttachment(row.id);
    ElMessage.success(TEXT.common.messages.deleteSuccess);
    load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.deleteFailed);
  }
};

onMounted(async () => {
  await Promise.all([loadMembers()]);
  load();
});
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.preview-frame {
  width: 100%;
  height: 520px;
  border: none;
}

.preview-media {
  max-width: 100%;
  max-height: 520px;
  display: block;
  margin: 0 auto;
}

.preview-error {
  color: var(--ctms-text-secondary);
  font-size: 13px;
  padding: 12px 0;
  text-align: center;
}
</style>
