<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  NButton, NCollapse, NCollapseItem, NEmpty, NSpace, NBadge,
  NPagination, NCheckbox, NDatePicker, NInput, NIcon,
} from 'naive-ui'
import { SearchOutline, SettingsOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'
import { useLiteraturePreview } from '../../composables/useLiteraturePreview'
import { usePagination } from '../../composables/usePagination'
import PageSkeleton from '../../components/common/PageSkeleton.vue'
import LiteratureCard from '../../components/literature/LiteratureCard.vue'
import LiteraturePreviewDrawer from '../../components/literature/LiteraturePreviewDrawer.vue'
import { trackAction } from '../../composables/useAnalytics'
import type { FeedItem } from '../../types'

const router = useRouter()
const toast = useToast()

const mustRead = ref<FeedItem[]>([])
const recommended = ref<FeedItem[]>([])
const related = ref<FeedItem[]>([])
const loading = ref(true)
const savedPmids = ref<Set<number>>(new Set())

// ── Filter state ──
const filterDateFrom = ref<number | null>(null)
const filterDateTo = ref<number | null>(null)
const filterQuery = ref('')

// ── Selection state ──
const selectedPmids = ref(new Set<number>())
const batchSaving = ref(false)
const batchDismissing = ref(false)

const allSelected = computed(() => {
  const all = [...mustRead.value, ...recommended.value, ...related.value]
  return all.length > 0 && all.every(i => selectedPmids.value.has(i.pmid))
})

function toggleSelect(pmid: number) {
  const s = new Set(selectedPmids.value)
  if (s.has(pmid)) { s.delete(pmid) } else { s.add(pmid) }
  selectedPmids.value = s
}

function toggleSelectAll() {
  if (allSelected.value) { clearSelection(); return }
  selectedPmids.value = new Set(
    [...mustRead.value, ...recommended.value, ...related.value].map(i => i.pmid)
  )
}

function clearSelection() {
  selectedPmids.value = new Set()
}

// ── Pagination with filter support ──
const { page, total, totalPages, goToPage } = usePagination({
  fetchFn: async (p: number) => {
    loading.value = true
    try {
      const params: Record<string, unknown> = { page: p, page_size: 20 }
      if (filterDateFrom.value) {
        const d = new Date(filterDateFrom.value)
        params.date_from = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
      }
      if (filterDateTo.value) {
        const d = new Date(filterDateTo.value)
        params.date_to = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
      }
      if (filterQuery.value.trim()) params.q = filterQuery.value.trim()
      const { data } = await api.get('/literature/feed', { params })
      mustRead.value = []
      recommended.value = []
      related.value = []
      for (const item of data.items || []) {
        if (item.priority === 'must_read') mustRead.value.push(item)
        else if (item.priority === 'recommended') recommended.value.push(item)
        else related.value.push(item)
      }
      total.value = data.total || 0
    } catch (e) { toast.apiError(e, '加载文献推送失败') }
    finally { loading.value = false }
  },
  pageSize: 20,
})

function applyFilters() {
  clearSelection()
  page.value = 1
  goToPage(1)
}

async function fetchSavedPmids() {
  try {
    const { data } = await api.get('/literature/saved')
    const items = data.items || data || []
    const itemsArr: Array<{ pmid: number } | number> = items
    savedPmids.value = new Set(itemsArr.map(i => (typeof i === 'number' ? i : i.pmid)))
  } catch (e) { toast.apiError(e, '加载收藏状态失败') }
}

onMounted(async () => {
  await Promise.all([goToPage(1), fetchSavedPmids()])
})

function goDetail(pmid: number) {
  api.post(`/literature/feed/${pmid}/read`).catch(() => {})
  router.push(`/app/literature/${pmid}`)
}

const { showPreview, previewPmid, openPreview: setPreviewPmid, closePreview } = useLiteraturePreview()

function openPreview(item: FeedItem) {
  setPreviewPmid(item.pmid)
}

async function handleSave(item: FeedItem) {
  const wasSaved = savedPmids.value.has(item.pmid)
  try {
    if (wasSaved) {
      await api.delete(`/literature/${item.pmid}/save`)
      const s = new Set(savedPmids.value)
      s.delete(item.pmid)
      savedPmids.value = s
      toast.success('已取消收藏')
    } else {
      await api.post(`/literature/${item.pmid}/save`)
      trackAction('save_literature', 'literature', String(item.pmid), { title: item.title })
      savedPmids.value = new Set([...savedPmids.value, item.pmid])
      toast.success('已收藏')
    }
  } catch (e) {
    toast.apiError(e, wasSaved ? '取消收藏失败' : '收藏失败')
  }
}

async function handleDismiss(item: FeedItem) {
  try {
    await api.post(`/literature/${item.pmid}/dismiss`)
    trackAction('feed_dismiss', 'literature', String(item.pmid))
    mustRead.value = mustRead.value.filter(i => i.pmid !== item.pmid)
    recommended.value = recommended.value.filter(i => i.pmid !== item.pmid)
    related.value = related.value.filter(i => i.pmid !== item.pmid)
  } catch (e) { toast.apiError(e, '忽略失败') }
}

// ── Batch actions ──
async function batchSave() {
  const pmids = [...selectedPmids.value]
  if (!pmids.length) return
  batchSaving.value = true
  try {
    const { data } = await api.post('/literature/feed/batch-save', { pmids })
    toast.success(`已收藏 ${data.saved} 篇`)
    savedPmids.value = new Set([...savedPmids.value, ...pmids])
    trackAction('feed_save', 'batch', pmids.join(','))
    clearSelection()
  } catch (e) { toast.apiError(e, '批量收藏失败') }
  finally { batchSaving.value = false }
}

async function batchDismiss() {
  const pmids = [...selectedPmids.value]
  if (!pmids.length) return
  batchDismissing.value = true
  try {
    const { data } = await api.post('/literature/feed/batch-dismiss', { pmids })
    toast.success(`已忽略 ${data.dismissed} 篇`)
    mustRead.value = mustRead.value.filter(i => !selectedPmids.value.has(i.pmid))
    recommended.value = recommended.value.filter(i => !selectedPmids.value.has(i.pmid))
    related.value = related.value.filter(i => !selectedPmids.value.has(i.pmid))
    clearSelection()
  } catch (e) { toast.apiError(e, '批量忽略失败') }
  finally { batchDismissing.value = false }
}
</script>

<template>
  <div class="feed-page">
    <!-- Header -->
    <div class="feed-header">
      <h2>📅 文献速览</h2>
      <NSpace>
        <NBadge :value="mustRead.length" type="error" style="cursor:default">🔴 必读</NBadge>
        <NBadge :value="recommended.length" type="warning" style="cursor:default">🟡 推荐</NBadge>
        <NBadge :value="related.length" type="default" style="cursor:default">⚪ 相关</NBadge>
      </NSpace>
    </div>

    <!-- Filter row -->
    <div class="filter-row">
      <NDatePicker
        v-model:value="filterDateFrom"
        type="date"
        placeholder="起始日期"
        size="small"
        style="width:140px"
        clearable
        @update:value="applyFilters"
      />
      <NDatePicker
        v-model:value="filterDateTo"
        type="date"
        placeholder="截止日期"
        size="small"
        style="width:140px"
        clearable
        @update:value="applyFilters"
      />
      <NInput
        v-model:value="filterQuery"
        placeholder="搜索标题/摘要…"
        size="small"
        style="width:200px"
        clearable
        @keyup.enter="applyFilters"
        @clear="filterQuery='';applyFilters()"
      />
      <NButton size="small" type="primary" :loading="loading" @click="applyFilters" class="sky-btn"><template #icon><NIcon size="14"><SearchOutline /></NIcon></template>搜索</NButton>
    </div>

    <!-- Batch toolbar -->
    <div v-if="selectedPmids.size > 0" class="batch-toolbar">
      <NCheckbox :checked="allSelected" @update:checked="toggleSelectAll" />
      <span class="batch-count">已选 {{ selectedPmids.size }} 篇</span>
      <NButton size="tiny" type="primary" :loading="batchSaving" @click="batchSave" class="sky-btn">批量收藏</NButton>
      <NButton size="tiny" :loading="batchDismissing" @click="batchDismiss" class="sky-btn">批量忽略</NButton>
      <NButton size="tiny" quaternary @click="clearSelection">取消选择</NButton>
    </div>

    <PageSkeleton :loading="loading">
      <NEmpty v-if="!mustRead.length && !recommended.length && !related.length"
              :description="filterDateFrom||filterDateTo||filterQuery ? '未找到匹配的文献推送' : '还没有文献推送。设置关注领域，明天早上7:00开始推送。'">
        <template #extra>
          <NButton type="primary" @click="router.push('/app/settings/interests')" class="sky-btn"><template #icon><NIcon size="14"><SettingsOutline /></NIcon></template>设置关注领域</NButton>
        </template>
      </NEmpty>

      <NCollapse v-if="mustRead.length" :default-expanded-names="['must']">
        <NCollapseItem name="must">
          <template #header><strong>🔥 必读 ({{ mustRead.length }})</strong></template>
          <div v-for="item in mustRead" :key="item.id" class="feed-item-row">
            <NCheckbox
              :checked="selectedPmids.has(item.pmid)"
              @update:checked="toggleSelect(item.pmid)"
              class="feed-checkbox"
            />
            <LiteratureCard
              :item="item" showSave :savedPmids="savedPmids"
              @detail="(i) => goDetail(i.pmid)"
              @preview="openPreview"
              @save="handleSave"
              @dismiss="handleDismiss"
            />
          </div>
        </NCollapseItem>
      </NCollapse>

      <NCollapse v-if="recommended.length">
        <NCollapseItem name="rec">
          <template #header><strong>🟡 推荐 ({{ recommended.length }})</strong></template>
          <div v-for="item in recommended" :key="item.id" class="feed-item-row">
            <NCheckbox
              :checked="selectedPmids.has(item.pmid)"
              @update:checked="toggleSelect(item.pmid)"
              class="feed-checkbox"
            />
            <LiteratureCard
              :item="item" showSave :savedPmids="savedPmids"
              @detail="(i) => goDetail(i.pmid)"
              @preview="openPreview"
              @save="handleSave"
              @dismiss="handleDismiss"
            />
          </div>
        </NCollapseItem>
      </NCollapse>

      <NCollapse v-if="related.length">
        <NCollapseItem name="rel">
          <template #header><strong>⚪ 相关 ({{ related.length }})</strong></template>
          <div v-for="item in related" :key="item.id" class="feed-item-row">
            <NCheckbox
              :checked="selectedPmids.has(item.pmid)"
              @update:checked="toggleSelect(item.pmid)"
              class="feed-checkbox"
            />
            <LiteratureCard
              :item="item" showSave :savedPmids="savedPmids"
              @detail="(i) => goDetail(i.pmid)"
              @preview="openPreview"
              @save="handleSave"
              @dismiss="handleDismiss"
            />
          </div>
        </NCollapseItem>
      </NCollapse>

      <NPagination
        v-if="totalPages > 1"
        :page="page" :item-count="total" :page-size="20"
        @update:page="goToPage"
        style="margin-top:24px;justify-content:center"
      />
    </PageSkeleton>

    <LiteraturePreviewDrawer
      :show="showPreview" :pmid="previewPmid"
      @close="closePreview"
      @goDetail="(lit) => goDetail(lit.pmid)"
    />
  </div>
</template>

<style scoped>
.feed-page { max-width: 1400px; margin: 0 auto; padding: 24px; }
.feed-header { display: flex; align-items: center; gap: 16px; margin-bottom: 12px; }
.feed-header h2 { margin: 0; }

.filter-row {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.batch-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  background: var(--bg-hover);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  margin-bottom: 12px;
}
.batch-count { font-size: 13px; font-weight: 600; color: var(--kw-pill-color); }
html.dark .batch-count { color: #6ab0e0; }

.feed-item-row {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  width: 100%;
}
.feed-item-row :deep(.lit-card) { flex: 1; min-width: 0; }
.feed-checkbox { margin-top: 16px; flex-shrink: 0; }

/* NCollapse/Item 内容全宽 */
.feed-page :deep(.n-collapse-item__content-inner) { width: 100%; }

/* ── Responsive: mobile (<768px) ── */
@media (max-width: 768px) {
  .feed-page { padding: 12px; }

  .feed-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .feed-header h2 { font-size: 20px; }

  .filter-row {
    flex-direction: column;
    gap: 6px;
  }
  /* override inline widths (140px / 200px) on filter controls */
  .filter-row > * { width: 100% !important; }

  .batch-toolbar {
    flex-wrap: wrap;
    gap: 6px;
  }

  .feed-item-row { gap: 4px; }
  .feed-checkbox { margin-top: 12px; }
}
</style>