<template>
  <div class="attachment-list-panel unified-shell">
    <div class="header">
      <span>{{ headerTitle }}</span>
      <AttachmentUploader
        v-if="!readonly"
        :study-id="studyId"
        :entity-type="entityType"
        :entity-id="entityId"
        @uploaded="load"
      />
    </div>
    <el-table :data="attachments" v-loading="loading" style="width: 100%" class="attachment-table" table-layout="fixed">
      <el-table-column prop="filename" :label="TEXT.common.labels.filename" show-overflow-tooltip />
      <el-table-column :label="TEXT.common.labels.size">
        <template #default="scope">{{ formatFileSize(scope.row.file_size ?? scope.row.size) }}</template>
      </el-table-column>
      <el-table-column :label="TEXT.common.labels.uploader" show-overflow-tooltip>
        <template #default="scope">
          {{ uploaderLabel(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="uploaded_at" :label="TEXT.common.labels.uploadedAt" show-overflow-tooltip>
        <template #default="scope">
          {{ displayDateTime(scope.row.uploaded_at) }}
        </template>
      </el-table-column>
      <el-table-column :label="TEXT.common.labels.actions" width="160">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="preview(scope.row)">
            {{ TEXT.common.labels.preview }}
          </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>
  </div>

  <el-dialog v-if="previewVisible" append-to-body 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 { computed, onMounted, ref, watch } 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 { isSystemAdmin } from "../../utils/roles";
import { usePermission } from "../../utils/permission";
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;
  title?: string;
  readonly?: boolean;
}>();

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

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 getDownloadUrl = (row: any) => {
  const token = localStorage.getItem("ctms_token");
  return row?.url || (token ? `/api/v1/attachments/${row.id}/download?token=${token}` : `/api/v1/attachments/${row.id}/download`);
};

const getPreviewUrl = (row: any) => {
  const token = localStorage.getItem("ctms_token");
  return token ? `/api/v1/attachments/${row.id}/preview?token=${token}` : `/api/v1/attachments/${row.id}/preview`;
};

const download = (row: any) => {
  const url = getDownloadUrl(row);
  const link = document.createElement("a");
  link.href = url;
  link.download = row?.filename || "download";
  link.rel = "noopener";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const getFileName = (row: any) => (row?.filename || "").toLowerCase();
const getMimeType = (row: any) => (row?.mime_type || row?.content_type || "").toLowerCase();

const detectPreviewType = (row: any) => {
  const mime = getMimeType(row);
  if (mime.startsWith("image/")) return "image";
  if (mime === "application/pdf") return "pdf";
  const name = getFileName(row);
  if ([".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".svg"].some((ext) => name.endsWith(ext))) return "image";
  if (name.endsWith(".pdf")) return "pdf";
  return "other";
};

const previewImage = async (downloadUrl: string) => {
  previewLoading.value = true;
  try {
    const token = localStorage.getItem("ctms_token");
    const headers: Record<string, string> = {};
    if (token) headers.Authorization = `Bearer ${token}`;
    const response = await fetch(downloadUrl, { headers });
    if (!response.ok) throw new Error("preview failed");
    const blob = await response.blob();
    if (previewObjectUrl.value) URL.revokeObjectURL(previewObjectUrl.value);
    previewObjectUrl.value = URL.createObjectURL(blob);
    previewUrl.value = previewObjectUrl.value;
  } catch {
    previewUrl.value = downloadUrl;
  } finally {
    previewLoading.value = false;
  }
};

const preview = (row: any) => {
  previewError.value = "";
  previewType.value = detectPreviewType(row);
  previewTitle.value = row?.filename || TEXT.common.labels.preview;
  const downloadUrl = getDownloadUrl(row);
  if (previewType.value === "image") {
    previewUrl.value = "";
    previewImage(downloadUrl);
  } else if (previewType.value === "pdf") {
    previewUrl.value = getPreviewUrl(row);
  } else {
    previewUrl.value = downloadUrl;
  }
  if (previewType.value === "other") {
    previewError.value = TEXT.common.messages.previewNotSupported;
  }
  previewVisible.value = true;
};

const canDelete = (row: any) => {
  if (props.readonly) return false;
  const action = props.entityType === "knowledge_note" ? "shared.library.write" : "file.attachment.delete";
  return isSystemAdmin(auth.user) || permission.can(action);
};

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

watch(previewVisible, (visible) => {
  if (!visible && previewObjectUrl.value) {
    URL.revokeObjectURL(previewObjectUrl.value);
    previewObjectUrl.value = "";
  }
});
</script>

<style scoped>
.attachment-list-panel {
  background: #ffffff;
  border: 0;
  border-radius: 0;
  box-shadow: none;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  border-bottom: 1px solid #eaf0f8;
}

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

.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>
