<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '@/api/admin'
import type { Bookmark } from '@/types'
import { VisibilityType } from '@/types'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const bookmarks = ref<Bookmark[]>([])
const total = ref(0)
const query = reactive({
  page: 1,
  pageSize: 20,
  search: ''
})

const userId = route.params.id as string

onMounted(() => {
  fetchBookmarks()
})

async function fetchBookmarks() {
  loading.value = true
  try {
    const response = await adminApi.getUserBookmarks(userId, query)
    if (response.success && response.data) {
      bookmarks.value = response.data.items
      total.value = response.data.total
    }
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  query.page = 1
  fetchBookmarks()
}

function handlePageChange(page: number) {
  query.page = page
  fetchBookmarks()
}

async function handleDelete(bookmark: Bookmark) {
  try {
    await ElMessageBox.confirm(
      `确定要删除书签 "${bookmark.title}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await adminApi.deleteUserBookmark(userId, bookmark.id)
    if (response.success) {
      ElMessage.success('删除成功')
      fetchBookmarks()
    }
  } catch {
    // 取消
  }
}

function getVisibilityText(visibility: VisibilityType) {
  const map = {
    [VisibilityType.Public]: '公开',
    [VisibilityType.Private]: '私密',
    [VisibilityType.Specified]: '指定设备'
  }
  return map[visibility] || '公开'
}

function formatDate(dateStr?: string) {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}
</script>

<template>
  <div class="user-bookmarks">
    <div class="page-header">
      <el-button @click="router.back()">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h2>用户书签</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="query.search"
        placeholder="搜索书签标题或URL"
        clearable
        style="width: 300px"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 书签列表 -->
    <el-table :data="bookmarks" v-loading="loading" class="bookmark-table">
      <el-table-column label="书签" min-width="300">
        <template #default="{ row }">
          <div class="bookmark-cell">
            <img
              v-if="row.icon"
              :src="row.icon"
              class="favicon"
              @error="($event.target as HTMLImageElement).style.display = 'none'"
            />
            <div class="bookmark-info">
              <div class="title">{{ row.title }}</div>
              <a :href="row.url" target="_blank" class="url">{{ row.url }}</a>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="标签" width="200">
        <template #default="{ row }">
          <div class="tags">
            <el-tag
              v-for="tag in row.tags.slice(0, 3)"
              :key="tag"
              size="small"
              type="info"
            >
              {{ tag }}
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="可见性" width="100">
        <template #default="{ row }">
          {{ getVisibilityText(row.visibility) }}
        </template>
      </el-table-column>

      <el-table-column label="访问次数" width="100" align="center" prop="visitCount" />

      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="query.page"
        :page-size="query.pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.user-bookmarks {
  .page-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;

    h2 {
      font-size: 20px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .search-bar {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
    background: #fff;
    padding: 16px;
    border-radius: 8px;
  }

  .bookmark-table {
    background: #fff;
    border-radius: 8px;
  }

  .bookmark-cell {
    display: flex;
    align-items: center;
    gap: 12px;

    .favicon {
      width: 24px;
      height: 24px;
      border-radius: 4px;
    }

    .bookmark-info {
      .title {
        font-weight: 500;
        color: #333;
      }

      .url {
        font-size: 12px;
        color: #999;
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 400px;
      }
    }
  }

  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

