import { mockNotes } from '../../utils/mock-data'
import type { Note } from '../../utils/mock-data'
import { formatRelativeTime } from '../../utils/time'

/** 带展示时间的备注项 */
interface NoteDisplay extends Note {
  timeLabel: string
}

Page({
  data: {
    pageState: 'loading' as 'loading' | 'empty' | 'error' | 'normal',
    notes: [] as NoteDisplay[],
    /** 系统状态栏高度（px），用于自定义导航栏顶部偏移 */
    statusBarHeight: 20,
  },

  onLoad() {
    const sysInfo = wx.getWindowInfo()
    this.setData({ statusBarHeight: sysInfo.statusBarHeight || 20 })
    this.loadData()
  },

  loadData() {
    this.setData({ pageState: 'loading' })

    setTimeout(() => {
      // TODO: 替换为真实 API 调用 GET /api/xcx/notes
      try {
        const notes: NoteDisplay[] = mockNotes.map((n) => ({
          ...n,
          timeLabel: formatRelativeTime(n.createdAt),
        }))
        this.setData({
          pageState: notes.length > 0 ? 'normal' : 'empty',
          notes,
        })
      } catch {
        this.setData({ pageState: 'error' })
      }
    }, 400)
  },

  /** 返回上一页 */
  onBack() {
    wx.navigateBack()
  },

  /** 错误态重试 */
  onRetry() {
    this.loadData()
  },

  /** 删除备注 */
  onDeleteNote(e: WechatMiniprogram.BaseEvent) {
    const noteId = e.currentTarget.dataset.id as string
    wx.showModal({
      title: '删除备注',
      content: '确定要删除这条备注吗？删除后无法恢复。',
      confirmColor: '#e34d59',
      success: (res) => {
        if (res.confirm) {
          const notes = this.data.notes.filter((n) => n.id !== noteId)
          this.setData({ notes })
          wx.showToast({ title: '已删除', icon: 'success' })
        }
      },
    })
  },

  /** 下拉刷新 */
  onPullDownRefresh() {
    this.loadData()
    wx.stopPullDownRefresh()
  },
})
