<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NCard, NButton, NInput, NPagination, NEmpty, NSkeleton, NTag, NPopconfirm } from 'naive-ui'
import { api } from '../../api/client'
import { toBeijingDate, toBeijingDateTime } from '../../utils/date'
import { useToast } from '../../composables/useToast'
import type { NoteItem } from '../../types'
import NoteEditModal from '../../components/notes/NoteEditModal.vue'

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

const notes = ref<NoteItem[]>([])
const loading = ref(true)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const searchQuery = ref('')

const showEdit = ref(false)
const editNoteId = ref('')
const editContent = ref('')
const editIsPrivate = ref(true)
const editSaving = ref(false)

// Delete
const deletingId = ref<string | null>(null)

function toggleExpand(id: string) {
  const n = notes.value.find(n => n.id === id)
  if (n) n._show = !n._show
}

async function loadNotes() {
  loading.value = true
  try {
    const params: Record<string, unknown> = { page: page.value, page_size: pageSize.value }
    if (searchQuery.value.trim()) params.q = searchQuery.value.trim()
    const { data } = await api.get('/notes/mine', { params })
    notes.value = (data.items || []).map((n: NoteItem) => ({ ...n, _show: false }))
    total.value = data.total || 0
  } catch (e) { toast.apiError(e, '加载笔记失败') }
  finally { loading.value = false }
}

onMounted(loadNotes)

let searchTimer: ReturnType<typeof setTimeout> | null = null
function onSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    page.value = 1
    loadNotes()
  }, 300)
}

function goToPage(n: number) {
  page.value = n
  loadNotes()
}

function goToLiterature(litId: string | undefined, pmid: number | null | undefined) {
  if (pmid) router.push(`/app/literature/${pmid}`)
  else if (litId) router.push(`/app/literature/${litId}`)
}

function openEdit(n: NoteItem) {
  editNoteId.value = n.id
  editContent.value = n.content
  editIsPrivate.value = n.is_private !== false
  showEdit.value = true
}

async function saveEdit() {
  if (!editContent.value.trim()) { toast.warning('笔记内容不能为空'); return }
  editSaving.value = true
  try {
    await api.put(`/notes/${editNoteId.value}`, { content: editContent.value, is_private: editIsPrivate.value })
    toast.success('笔记已更新')
    showEdit.value = false
    await loadNotes()
  } catch (e) { toast.apiError(e, '更新失败') }
  finally { editSaving.value = false }
}

async function handleDelete(nid: string) {
  deletingId.value = nid
  try {
    await api.delete(`/notes/${nid}`)
    toast.success('笔记已删除')
    await loadNotes()
  } catch (e) { toast.apiError(e, '删除失败') }
  finally { deletingId.value = null }
}

function formatDate(d: string | undefined) {
  if (!d) return ''
  return d.length > 10 ? toBeijingDateTime(d) : toBeijingDate(d)
}
</script>

<template>
  <div style="max-width:1400px;margin:0 auto;padding:24px">
    <!-- Header -->
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:8px">
      <h2 style="margin:0">📝 我的笔记</h2>
      <div style="display:flex;gap:8px">
        <NInput
          v-model:value="searchQuery"
          placeholder="搜索笔记内容或文献标题…"
          clearable
          size="small"
          style="width:220px"
          @input="onSearchInput"
          @clear="searchQuery='';loadNotes()"
        />
      </div>
    </div>

    <!-- Loading -->
    <NSkeleton v-if="loading" text :repeat="6" />

    <!-- Empty -->
    <NEmpty v-else-if="!notes.length" style="padding:48px 0" :description="searchQuery ? '未找到匹配的笔记' : '还没有写过笔记。在阅读文献时添加笔记吧！'" />

    <!-- Note list -->
    <div v-else style="display:flex;flex-direction:column;gap:16px">
      <NCard v-for="n in notes" :key="n.id" size="small" hoverable>
        <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px">
          <!-- Content -->
          <div style="flex:1;min-width:0">
            <!-- Literature title link -->
            <div style="margin-bottom:6px">
              <NTag size="tiny" :bordered="false" type="info" style="margin-right:4px">文献</NTag>
              <span class="note-lit-title" @click.stop="goToLiterature(n.literature_id, n.pmid)">{{ n.literature_title || '未知文献' }}</span>
            </div>
            <!-- Content body with truncation -->
            <div v-if="n._show" key="exp" class="note-body">
              {{ n.content }}
            </div>
            <div v-else key="col" class="note-body clamp-3">
              {{ n.content }}
            </div>
            <div v-if="n.content && n.content.length > 60" class="expand-toggle" @click="toggleExpand(n.id)">
              {{ n._show ? '收起' : '展开全部' }}
            </div>
            <!-- Quote text -->
            <div v-if="n.quote_text" class="note-quote">
              "{{ n.quote_text }}"
            </div>
            <!-- Meta + Actions -->
            <div class="note-meta">
              <span>{{ formatDate(n.created_at) }}</span>
              <span v-if="n.updated_at && n.updated_at !== n.created_at"> · 编辑于 {{ formatDate(n.updated_at) }}</span>
              <NTag v-if="n.is_private === false" size="tiny" :bordered="false" style="font-size:10px">公开</NTag>
              <span style="flex:1"></span>
              <NButton size="tiny" text @click="openEdit(n)">编辑</NButton>
              <NPopconfirm @positive="handleDelete(n.id)">
                <template #trigger>
                  <NButton size="tiny" text type="error" :loading="deletingId === n.id">删除</NButton>
                </template>
                确认删除此笔记？
              </NPopconfirm>
            </div>
          </div>
        </div>
      </NCard>
    </div>

    <!-- Pagination -->
    <NPagination
      v-if="total > pageSize"
      :page="page"
      :item-count="total"
      :page-size="pageSize"
      @update:page="goToPage"
      style="margin-top:16px;justify-content:center"
    />

    <!-- Edit modal -->
    <NoteEditModal
      :show="showEdit"
      :content="editContent"
      :is-private="editIsPrivate"
      :saving="editSaving"
      @update:show="(v: boolean) => showEdit = v"
      @update:content="(v: string) => editContent = v"
      @update:is-private="(v: boolean) => editIsPrivate = v"
      @save="saveEdit"
    />
  </div>
</template>

<style scoped>
.note-body { font-size:15px; line-height:1.8; color:var(--text-primary); white-space:pre-wrap; word-break:break-word; }
.clamp-3 { overflow:hidden; max-height:81px; }
.expand-toggle { font-size:12px; color:var(--primary-color, #3a7bc8); cursor:pointer; margin-top:2px; }
.expand-toggle:hover { text-decoration:underline; }
.note-quote { margin-top:6px; padding:6px 10px; background:var(--bg-card); border-left:3px solid var(--primary-color, #1a5276); font-size:12px; color:var(--text-secondary); border-radius:2px; font-style:italic; }
.note-meta { margin-top:8px; display:flex; align-items:center; gap:10px; font-size:11px; color:var(--text-muted); flex-wrap:wrap; }
.note-lit-title { font-size:14px; color:var(--primary-color, #3a7bc8); cursor:pointer; }
.note-lit-title:hover { text-decoration:underline; }
</style>
