<script setup>
import { computed, nextTick, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Loading, Search } from '@element-plus/icons-vue'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

import { parseBookmarkHTML } from '@/utils/bookmarkParser'
import { useLinksStore } from '@/stores/links'
import { storeToRefs } from 'pinia'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:modelValue'])

const linksStore = useLinksStore()
const { allTags } = storeToRefs(linksStore)
const uploadRef = ref()
const tableRef = ref()

// 确保 store 已加载
linksStore.ensureLoaded()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

const isParsing = ref(false)
const parsedBookmarks = ref([])
const selectedBookmarkIds = ref(new Set()) // 使用 Set 提高性能
const searchKeyword = ref('')
const isImporting = ref(false)
const currentPage = ref(1)
const pageSize = 50
const isSyncingSelection = ref(false) // 防止同步时触发选择事件

// 过滤后的书签列表（用于搜索）
const filteredBookmarks = computed(() => {
  if (!searchKeyword.value.trim()) {
    return parsedBookmarks.value
  }

  const keyword = searchKeyword.value.toLowerCase()
  return parsedBookmarks.value.filter((bookmark) => {
    return (
      bookmark.title.toLowerCase().includes(keyword) ||
      bookmark.url.toLowerCase().includes(keyword) ||
      (bookmark.folderPath && bookmark.folderPath.toLowerCase().includes(keyword))
    )
  })
})

// 分页后的书签列表
const paginatedBookmarks = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return filteredBookmarks.value.slice(start, end)
})

// 是否需要分页
const needPagination = computed(() => filteredBookmarks.value.length > 100)

// 总页数
const totalPages = computed(() => {
  if (!needPagination.value) return 1
  return Math.ceil(filteredBookmarks.value.length / pageSize)
})

// 统计信息
const stats = computed(() => {
  const total = filteredBookmarks.value.length
  const selected = selectedBookmarkIds.value.size
  return { total, selected }
})

// 全选状态
const isAllSelected = computed(() => {
  if (paginatedBookmarks.value.length === 0) return false
  return paginatedBookmarks.value.every((bookmark) => selectedBookmarkIds.value.has(bookmark.id))
})

// 部分选中状态
const isIndeterminate = computed(() => {
  const selectedCount = paginatedBookmarks.value.filter((bookmark) =>
    selectedBookmarkIds.value.has(bookmark.id)
  ).length
  return selectedCount > 0 && selectedCount < paginatedBookmarks.value.length
})

// 处理文件上传
async function handleFileUpload(uploadFile) {
  const file = uploadFile?.raw
  if (!file) return

  // 验证文件类型
  if (!file.name.toLowerCase().endsWith('.html')) {
    ElMessage.error('请上传 HTML 格式的书签文件')
    uploadRef.value?.clearFiles()
    return
  }

  // 验证文件大小（10MB）
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('文件过大，请选择小于 10MB 的文件')
    uploadRef.value?.clearFiles()
    return
  }

  isParsing.value = true
  try {
    const text = await file.text()
    const bookmarks = parseBookmarkHTML(text)
    parsedBookmarks.value = bookmarks
    selectedBookmarkIds.value = new Set()
    searchKeyword.value = ''
    currentPage.value = 1
    ElMessage.success(`成功解析 ${bookmarks.length} 条书签`)
  } catch (error) {
    console.error(error)
    ElMessage.error(error.message || '解析文件失败，请确认这是浏览器导出的书签文件')
    parsedBookmarks.value = []
    selectedBookmarkIds.value = new Set()
  } finally {
    isParsing.value = false
    uploadRef.value?.clearFiles()
  }
}

// 更新书签的标签
function updateBookmarkTags(bookmarkId, tags) {
  const bookmark = parsedBookmarks.value.find((b) => b.id === bookmarkId)
  if (bookmark) {
    bookmark.tags = Array.isArray(tags) ? tags.filter(Boolean) : []
  }
}

// 更新书签的备注
function updateBookmarkDescription(bookmarkId, description) {
  const bookmark = parsedBookmarks.value.find((b) => b.id === bookmarkId)
  if (bookmark) {
    bookmark.description = description || ''
  }
}

// 处理单个选择变化
function handleSelectionChange(selection, row) {
  if (isSyncingSelection.value) return // 如果正在同步选择状态，忽略事件
  if (!row || !row.id) return
  
  const bookmarkId = row.id
  if (selection.includes(row)) {
    selectedBookmarkIds.value.add(bookmarkId)
  } else {
    selectedBookmarkIds.value.delete(bookmarkId)
  }
  // 触发响应式更新
  selectedBookmarkIds.value = new Set(selectedBookmarkIds.value)
}

// 处理全选变化
function handleSelectAll(selection) {
  if (isSyncingSelection.value) return // 如果正在同步选择状态，忽略事件
  
  if (selection && selection.length > 0) {
    // 全选当前页
    paginatedBookmarks.value.forEach((bookmark) => {
      if (bookmark && bookmark.id) {
        selectedBookmarkIds.value.add(bookmark.id)
      }
    })
  } else {
    // 取消全选当前页
    paginatedBookmarks.value.forEach((bookmark) => {
      if (bookmark && bookmark.id) {
        selectedBookmarkIds.value.delete(bookmark.id)
      }
    })
  }
  // 触发响应式更新
  selectedBookmarkIds.value = new Set(selectedBookmarkIds.value)
}

// 格式化日期
function formatDate(timestamp) {
  if (!timestamp) return '-'
  try {
    return format(new Date(timestamp * 1000), 'yyyy-MM-dd HH:mm', { locale: zhCN })
  } catch {
    return '-'
  }
}

// 处理导入
async function handleImport() {
  const selectedCount = selectedBookmarkIds.value.size
  if (selectedCount === 0) {
    ElMessage.warning('请至少选择一条书签')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要导入 ${selectedCount} 条书签吗？`,
      '确认导入',
      {
        confirmButtonText: '导入',
        cancelButtonText: '取消',
        type: 'info',
      }
    )

    isImporting.value = true

    // 获取选中的书签
    const selectedBookmarks = parsedBookmarks.value.filter((bookmark) =>
      selectedBookmarkIds.value.has(bookmark.id)
    )

    if (selectedBookmarks.length !== selectedCount) {
      console.warn('选择的书签数量不匹配', {
        selectedCount,
        foundCount: selectedBookmarks.length,
        selectedIds: Array.from(selectedBookmarkIds.value),
        parsedIds: parsedBookmarks.value.map((b) => b.id),
      })
    }

    // 转换为应用格式
    const bookmarkItems = selectedBookmarks.map((bookmark) => ({
      title: bookmark.title,
      url: bookmark.url,
      icon: bookmark.icon,
      description: bookmark.description || '',
      tags: bookmark.tags || [],
      projectIds: [],
      createdAt: bookmark.addDate ? new Date(bookmark.addDate * 1000) : new Date(),
      updatedAt: bookmark.addDate ? new Date(bookmark.addDate * 1000) : new Date(),
    }))

    // 调用 store 方法导入
    const result = await linksStore.importBrowserBookmarks(bookmarkItems)

    // 显示结果
    let message = `已成功导入 ${result.success} 条书签`
    if (result.skipped > 0) {
      message += `，${result.skipped} 条已存在已跳过`
    }
    if (result.failed > 0) {
      message += `，${result.failed} 条导入失败`
    }
    ElMessage.success(message)

    // 关闭对话框
    visible.value = false
    // 重置状态
    parsedBookmarks.value = []
    selectedBookmarkIds.value = new Set()
    searchKeyword.value = ''
    currentPage.value = 1
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      return
    }
    console.error(error)
    ElMessage.error(error.message || '导入失败')
  } finally {
    isImporting.value = false
  }
}

// 关闭对话框时重置
function handleClose() {
  parsedBookmarks.value = []
  selectedBookmarkIds.value = new Set()
  searchKeyword.value = ''
  currentPage.value = 1
}

// 处理分页变化
function handlePageChange(page) {
  currentPage.value = page
  // 分页变化后，同步表格选择状态
  nextTick(() => {
    syncTableSelection()
  })
}

// 同步表格选择状态
function syncTableSelection() {
  if (!tableRef.value) return
  isSyncingSelection.value = true // 设置标志，防止触发选择事件
  
  // 清除当前选择状态
  tableRef.value.clearSelection()
  
  nextTick(() => {
    if (!tableRef.value) {
      isSyncingSelection.value = false
      return
    }
    
    // 根据选中ID重新设置选择状态
    paginatedBookmarks.value.forEach((bookmark) => {
      if (bookmark && bookmark.id && selectedBookmarkIds.value.has(bookmark.id)) {
        tableRef.value.toggleRowSelection(bookmark, true, false) // 第三个参数 false 表示不触发选择事件
      }
    })
    
    isSyncingSelection.value = false // 重置标志
  })
}

// 监听分页数据变化，更新表格选择状态
watch(
  paginatedBookmarks,
  () => {
    syncTableSelection()
  },
  { immediate: true }
)

// 监听可见性变化，同步选择状态
watch(
  visible,
  (newVisible) => {
    if (newVisible && parsedBookmarks.value.length > 0) {
      nextTick(() => {
        syncTableSelection()
      })
    }
  }
)

// 添加调试信息的方法（开发阶段使用）
function debugSelectionState() {
  console.log('当前选中的ID:', Array.from(selectedBookmarkIds.value))
  console.log('当前页书签:', paginatedBookmarks.value.map(b => ({ id: b.id, title: b.title })))
  console.log('表格引用:', !!tableRef.value)
}
</script>

<template>
  <el-dialog
    v-model="visible"
    title="导入浏览器书签"
    width="80vw"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 文件上传区域 -->
    <section v-if="parsedBookmarks.length === 0" style="margin-bottom: 24px">
      <el-upload
        ref="uploadRef"
        drag
        accept=".html"
        :show-file-list="false"
        :auto-upload="false"
        :disabled="isParsing"
        @change="handleFileUpload"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">拖拽 HTML 文件到此处或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">支持 Chrome、Firefox、Edge 等浏览器导出的书签文件（.html）</div>
        </template>
      </el-upload>
      <div v-if="isParsing" style="text-align: center; padding: 20px">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span style="margin-left: 8px">正在解析文件...</span>
      </div>
    </section>

    <!-- 书签列表区域 -->
    <section v-else>
      <!-- 搜索和统计 -->
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索标题、URL 或文件夹"
          clearable
          style="width: 300px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <div style="color: var(--el-text-color-secondary); font-size: 14px">
          总书签数: {{ stats.total }} | 已选择: {{ stats.selected }}
        </div>
      </div>

      <!-- 表格 -->
      <el-table
        ref="tableRef"
        :data="paginatedBookmarks"
        style="width: 100%"
        max-height="500"
        row-key="id"
        @select="handleSelectionChange"
        @select-all="handleSelectAll"
      >
        <el-table-column
          type="selection"
          width="55"
          :reserve-selection="true"
        />

        <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <a :href="row.url" target="_blank" rel="noopener noreferrer" style="color: var(--el-color-primary)">
              {{ row.title }}
            </a>
          </template>
        </el-table-column>

        <el-table-column prop="url" label="URL" min-width="200" show-overflow-tooltip />

        <el-table-column label="标签" width="200">
          <template #default="{ row }">
            <el-select
              v-model="row.tags"
              multiple
              filterable
              :reserve-keyword="false"
              allow-create
              default-first-option
              placeholder="添加标签"
              size="small"
              @change="(tags) => updateBookmarkTags(row.id, tags)"
              >
              <el-option v-for="tag in allTags" :key="tag" :label="tag" :value="tag" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="备注" width="200">
          <template #default="{ row }">
            <el-input
              v-model="row.description"
              type="textarea"
              :rows="2"
              placeholder="添加备注"
              size="small"
              @blur="(e) => updateBookmarkDescription(row.id, e.target.value)"
            />
          </template>
        </el-table-column>

        <el-table-column prop="folderPath" label="来源文件夹" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.folderPath" style="color: var(--el-text-color-secondary); font-size: 12px">
              {{ row.folderPath }}
            </span>
            <span v-else style="color: var(--el-text-color-placeholder)">-</span>
          </template>
        </el-table-column>

        <el-table-column label="添加时间" width="150">
          <template #default="{ row }">
            <span style="color: var(--el-text-color-secondary); font-size: 12px">
              {{ formatDate(row.addDate) }}
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div v-if="needPagination" style="margin-top: 16px; display: flex; justify-content: flex-end">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="filteredBookmarks.length"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </section>

    <!-- 底部按钮 -->
    <template #footer>
      <div style="display: flex; justify-content: flex-end; gap: 12px">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="selectedBookmarkIds.size === 0 || isImporting"
          :loading="isImporting"
          @click="handleImport"
        >
          {{ isImporting ? '导入中...' : `导入选中项 (${selectedBookmarkIds.size})` }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

