<script setup lang="ts">
import { h, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NCard, NTag, NButton, NDataTable, NEmpty, NSkeleton, NPagination, NSelect } from 'naive-ui'
import { api } from '../../api/client'

const router = useRouter()
const loading = ref(true)
const items = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(30)
const activeType = ref<string | null>(null)
const days = ref(7)

const activityTypeColors: Record<string, string> = {
  page_view: '#2080f0',
  search: '#f0a020',
  view_literature: '#18a058',
  save_literature: '#7c4dff',
  export: '#d03050',
  browse_cancer: '#eb2f96',
  browse_journals: '#13c2c2',
  click_tag: '#fa8c16',
}
const activityTypeLabels: Record<string, string> = {
  page_view: '页面访问', search: '搜索', view_literature: '查看文献',
  save_literature: '收藏文献', export: '导出', browse_cancer: '浏览癌种',
  browse_journals: '浏览期刊', click_tag: '点击标签',
}

const typeOptions = computed(() => {
  const unique = new Set(items.value.map((i: any) => i.activity_type))
  return Array.from(unique).map(t => ({
    label: activityTypeLabels[t as string] || t,
    value: t,
  }))
})

function relativeTime(isoStr: string | null): string {
  if (!isoStr) return ''
  const diff = Math.floor((Date.now() - new Date(isoStr).getTime()) / 1000)
  if (diff < 60) return '刚刚'
  if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`
  if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`
  if (diff < 2592000) return `${Math.floor(diff / 86400)} 天前`
  return isoStr.slice(0, 10)
}

function formatDuration(s: number | null): string {
  if (!s || s <= 0) return ''
  if (s < 60) return `${s}s`
  if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`
  return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`
}

function targetSummary(row: any): string {
  const detail = row.detail || {}
  if (row.activity_type === 'search') return detail.keywords || `搜索 ${row.target_id || ''}`
  if (row.activity_type === 'view_literature') return detail.title || `文献 PMID ${row.target_id}`
  if (row.activity_type === 'page_view') return detail.title || detail.path || row.target_id || ''
  if (row.activity_type === 'save_literature') return detail.title || `收藏文献 ${row.target_id}`
  return detail.title || row.target_id || ''
}

function handleRowClick(row: any) {
  if (row.activity_type === 'view_literature' || row.activity_type === 'save_literature') {
    if (row.target_id) router.push(`/app/literature/${row.target_id}`)
  } else if (row.target_type === 'route' && row.detail?.path) {
    router.push(row.detail.path)
  }
}

const columns = [
  {
    title: '类型', key: 'activity_type', width: 100,
    render: (r: any) => {
      const color = activityTypeColors[r.activity_type]
      const label = activityTypeLabels[r.activity_type] || r.activity_type
      return h(NTag as any, {
        size: 'tiny',
        color: color ? { color } : undefined,
        bordered: false,
      }, { default: () => label })
    },
  },
  {
    title: '内容', key: 'target', ellipsis: { tooltip: true },
    render: (r: any) => targetSummary(r),
  },
  {
    title: '停留', key: 'duration', width: 70,
    render: (r: any) => r.activity_type === 'page_view' ? formatDuration(r.duration_seconds) : '',
  },
  {
    title: '时间', key: 'created_at', width: 120,
    render: (r: any) => {
      const rt = relativeTime(r.created_at)
      return h('span', { title: r.created_at }, rt)
    },
  },
]
const scrollX = 590

onMounted(loadData)
async function loadData() {
  loading.value = true
  try {
    const params: Record<string, any> = { page: page.value, page_size: pageSize.value, days: days.value }
    if (activeType.value) params.activity_type = activeType.value
    const { data } = await api.get('/settings/activity-history', { params })
    items.value = data.items || []
    total.value = data.total || 0
  } catch (e) {
    // silent
  } finally {
    loading.value = false
  }
}

function onTypeChange(val: string | null) {
  activeType.value = val
  page.value = 1
  loadData()
}
function onDaysChange(val: number) {
  days.value = val
  page.value = 1
  loadData()
}
</script>

<template>
  <div style="max-width:1400px;margin:0 auto;padding:24px">
    <h2 style="margin:0">🕐 浏览历史</h2>
    <div style="height:12px" />

    <!-- 筛选栏 -->
    <NCard size="small" style="margin-bottom:16px">
      <div style="display:flex;gap:12px;flex-wrap:wrap;align-items:center">
        <NButton size="tiny" :type="days===7?'primary':'default'" @click="onDaysChange(7)">近 7 天</NButton>
        <NButton size="tiny" :type="days===30?'primary':'default'" @click="onDaysChange(30)">近 30 天</NButton>
        <NButton size="tiny" :type="days===90?'primary':'default'" @click="onDaysChange(90)">近 90 天</NButton>
        <div style="flex:1" />
        <NSelect v-if="typeOptions.length" v-model:value="activeType" :options="typeOptions"
          placeholder="筛选类型" style="width:160px" size="tiny" clearable @update:value="onTypeChange" />
        <NButton size="tiny" secondary @click="activeType=null;onTypeChange(null)" v-if="activeType">清除筛选</NButton>
      </div>
    </NCard>

    <!-- 列表 -->
    <NSkeleton v-if="loading" text :repeat="8" />
    <NEmpty v-else-if="!items.length" description="暂无浏览记录" style="padding:48px 0" />
    <template v-else>
      <NDataTable :columns="columns" :data="items" size="small" :bordered="false"
        :scroll-x="scrollX"
        :row-props="(r: any) => ({ style: 'cursor:pointer', onClick: () => handleRowClick(r) })" />
      <div v-if="total > pageSize" style="display:flex;justify-content:center;margin-top:16px">
        <NPagination :page="page" :page-size="pageSize" :item-count="total" @update:page="p => { page=p; loadData() }" />
      </div>
    </template>
  </div>
</template>
