<template>
  <div class="file-manage">
    <!-- Header -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">文件管理</h2>
        <p class="page-subtitle">管理您的文档集合</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleUpload" class="upload-btn">
          <el-icon><Upload /></el-icon>
          <span>上传文件</span>
        </el-button>
      </div>
    </div>

    <!-- Stats Cards -->
    <div class="stats-grid">
      <div
        class="stat-card stat-total"
        :class="{ active: filterStatus === '' }"
        @click="filterStatus = ''"
      >
        <div class="stat-glow"></div>
        <div class="stat-inner">
          <div class="stat-icon-wrap">
            <el-icon size="24"><Document /></el-icon>
          </div>
          <div class="stat-info">
            <span class="stat-value">{{ files.length }}</span>
            <span class="stat-label">总文件数</span>
          </div>
        </div>
      </div>
      <div
        class="stat-card stat-completed"
        :class="{ active: filterStatus === 'completed' }"
        @click="filterStatus = filterStatus === 'completed' ? '' : 'completed'"
      >
        <div class="stat-glow"></div>
        <div class="stat-inner">
          <div class="stat-icon-wrap">
            <el-icon size="24"><CircleCheckFilled /></el-icon>
          </div>
          <div class="stat-info">
            <span class="stat-value">{{ completedFiles }}</span>
            <span class="stat-label">已完成</span>
          </div>
        </div>
      </div>
      <div
        class="stat-card stat-processing"
        :class="{ active: filterStatus === 'processing' }"
        @click="filterStatus = filterStatus === 'processing' ? '' : 'processing'"
      >
        <div class="stat-glow"></div>
        <div class="stat-inner">
          <div class="stat-icon-wrap">
            <el-icon size="24"><Loading /></el-icon>
          </div>
          <div class="stat-info">
            <span class="stat-value">{{ processingFiles.length }}</span>
            <span class="stat-label">处理中</span>
          </div>
        </div>
      </div>
      <div
        class="stat-card stat-failed"
        :class="{ active: filterStatus === 'failed' }"
        @click="filterStatus = filterStatus === 'failed' ? '' : 'failed'"
      >
        <div class="stat-glow"></div>
        <div class="stat-inner">
          <div class="stat-icon-wrap">
            <el-icon size="24"><CircleCloseFilled /></el-icon>
          </div>
          <div class="stat-info">
            <span class="stat-value">{{ failedFiles }}</span>
            <span class="stat-label">失败</span>
          </div>
        </div>
      </div>
    </div>

    <!-- File List Container -->
    <div class="file-container" v-loading="loading && isInitialLoad">
      <!-- Empty State -->
      <div v-if="!loading && !isInitialLoad && filteredFiles.length === 0 && !uploading" class="empty-state">
        <div class="empty-illustration">
          <div class="orbit orbit-1"></div>
          <div class="orbit orbit-2"></div>
          <div class="orbit orbit-3"></div>
          <div class="empty-core">
            <el-icon size="40"><FolderOpened /></el-icon>
          </div>
        </div>
        <h3 class="empty-title">暂无文件</h3>
        <p class="empty-desc">上传您的第一个文档，开启智能处理之旅</p>
      </div>

      <!-- Files Table -->
      <div v-else class="files-table-wrapper">
        <!-- Table Header -->
        <div class="table-header">
          <div class="table-select">
            <el-checkbox
              :model-value="isAllSelected"
              @change="toggleSelectAll"
              class="select-all"
            >
              <span v-if="selectedCount > 0" class="selected-text">已选择 {{ selectedCount }} 项</span>
              <span v-else>全选</span>
            </el-checkbox>
          </div>
          <div class="table-actions" v-if="selectedCount > 0">
            <el-button type="danger" size="small" plain @click="clearSelection" class="batch-clear-btn">
              <el-icon><Close /></el-icon>
              <span>清除选择</span>
            </el-button>
            <el-button type="danger" size="small" plain @click="batchDelete" class="batch-delete-btn">
              <el-icon><Delete /></el-icon>
              <span>批量删除</span>
            </el-button>
          </div>
        </div>

        <!-- Table Body -->
        <div class="files-table">
          <div
            v-for="(file, index) in filteredFiles"
            :key="file.id"
            class="file-row"
            :class="{
              'is-selected': isSelected(file.id),
              'is-processing': file.status === 'processing',
              'row-animated': isInitialLoad
            }"
            :style="{ '--delay': index * 0.04 + 's' }"
            @click="toggleSelect(file.id)"
          >
            <!-- Select Checkbox -->
            <div class="col-select" @click.stop>
              <el-checkbox
                :model-value="isSelected(file.id)"
                @change="toggleSelect(file.id)"
              />
            </div>

            <!-- File Icon -->
            <div class="col-icon">
              <div class="file-type-icon" :style="{ '--type-color': getTypeColor(file.file_type) }">
                <el-icon size="18">
                  <component :is="getFileIcon(file.file_type)" />
                </el-icon>
              </div>
            </div>

            <!-- File Name -->
            <div class="col-name">
              <span class="filename-text">{{ file.filename }}</span>
              <span class="file-ext">{{ getFileExt(file.filename) }}</span>
            </div>

            <!-- Size -->
            <div class="col-size">
              {{ formatSize(file.size) }}
            </div>

            <!-- Date -->
            <div class="col-date">
              {{ formatDate(file.created_at) }}
            </div>

            <!-- Status -->
            <div class="col-status">
              <div class="status-pill" :class="'status-' + file.status">
                <span class="status-dot"></span>
                <span class="status-text">{{ getStatusText(file.status) }}</span>
              </div>
            </div>

            <!-- Actions -->
            <div class="col-actions" @click.stop>
              <el-tooltip content="预览" placement="top" v-if="file.status === 'completed'">
                <el-button text size="small" class="action-btn preview" @click="handlePreview(file)">
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-button text size="small" class="action-btn delete" @click="openDeleteDialog(file)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Upload Dialog -->
    <el-dialog v-model="uploadDialogVisible" title="上传文件" width="520px" class="upload-dialog" :close-on-click-modal="false">
      <div class="upload-area" @click="triggerUpload">
        <el-upload
          ref="uploadRef"
          class="upload-component"
          :auto-upload="false"
          :limit="10"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :file-list="fileList"
          drag
          multiple
          accept=".pdf,.docx,.doc,.xlsx,.xls,.csv,.epub,.md,.txt"
          style="display: none;"
        />
        <div class="upload-content">
          <div class="upload-illustration">
            <div class="upload-ring"></div>
            <div class="upload-core">
              <el-icon size="32"><UploadFilled /></el-icon>
            </div>
          </div>
          <div class="upload-text">
            拖拽文件到此处，或 <em>点击选择</em>
          </div>
          <div class="upload-hint">
            支持 PDF、DOCX、Excel、EPUB、Markdown 等格式
          </div>
        </div>
      </div>

      <!-- Selected Files -->
      <div v-if="fileList.length > 0" class="selected-area">
        <div class="selected-header">
          <span>已选择 <strong>{{ fileList.length }}</strong> 个文件</span>
          <el-button text size="small" @click="fileList = []">清空</el-button>
        </div>
        <div class="selected-list">
          <div v-for="item in fileList" :key="item.uid" class="selected-item">
            <el-icon size="14"><Document /></el-icon>
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploading" :disabled="fileList.length === 0">
          开始上传
        </el-button>
      </template>
    </el-dialog>
  </div>

  <Teleport to="body">
    <Transition name="fade">
      <div
        v-if="previewVisible"
        class="preview-backdrop"
        @click="previewVisible = false"
      ></div>
    </Transition>

    <Transition name="slide-right">
      <div v-if="previewVisible" class="preview-modal">
        <div class="preview-header">
          <div class="header-title">
            <el-icon class="title-icon"><Document /></el-icon>
            <span class="filename">{{ previewFile?.filename }}</span>
          </div>
          <el-button class="close-btn" text @click="previewVisible = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>

        <div class="preview-tabs-wrapper">
          <div class="preview-tabs">
            <button
              class="tab-item"
              :class="{ active: previewMode === 'source' }"
              @click="switchPreviewMode('source')"
            >
              源文件
            </button>
            <button
              class="tab-item"
              :class="{ active: previewMode === 'markdown' }"
              @click="switchPreviewMode('markdown')"
            >
              Markdown
            </button>
            <div class="tab-indicator" :class="{ 'at-right': previewMode === 'markdown' }"></div>
          </div>
        </div>

        <div class="preview-content" v-loading="previewLoading">
          <iframe v-if="isPdfPreview && pdfDataUrl" :src="pdfDataUrl" class="pdf-viewer"></iframe>
          <pre v-else-if="previewContent" class="code-content">{{ previewContent }}</pre>
          <div v-else-if="!previewLoading && !isPdfPreview" class="preview-empty">
            <el-icon size="32"><Document /></el-icon>
            <span>暂无内容</span>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>

  <DeleteDialog
    v-model:visible="deleteDialogVisible"
    title="删除文件"
    :item-name="pendingDeleteFile?.filename || ''"
    detail-text="该操作会移除原始文件以及关联的处理结果，请确认当前项目内不再需要它。"
    warning-text="删除后不可恢复，文件相关的分割结果和后续数据将一并失效。"
    confirm-text="确认删除文件"
    :loading="deletingFile"
    @confirm="confirmDeleteFile"
  />
</template>

<script lang="ts" src="../page-logic/ProjectFilePage.ts"></script>
<style scoped src="../styles/pages/project-file.css"></style>
