<template>
  <ion-app>
    <div class="container">
      <Header :title="headerTitle" :onAction="handleAddNote" actionIcon="create" leftType="settings" :onLeftAction="handleSettingsPress" :onFolderToggle="handleFolderToggle" :isFolderExpanded="isFolderExpanded" :onTitlePress="handleFolderToggle" />

      <!-- 悬浮文件夹列表 - 使用绝对定位实现 -->
      <div
        v-if="isFolderExpanded"
        style="position: absolute; top: 50px; left: 10%; right: 10%; z-index: 1000; background-color: var(--background-card); border-radius: 8px; box-shadow: 0 2px 4px var(--shadow); border: 1px solid #f0ece7; overflow: hidden">
        <FolderManage
          :allCount="notes.length"
          :starredCount="starredNotesCount"
          :trashCount="0"
          :archiveCount="0"
          :selectedFolder="currentFolder"
          :onAllClick="
            () => {
              setCurrentFolder('all')
              setIsFolderExpanded(false)
            }
          "
          :onStarredClick="
            () => {
              setCurrentFolder('starred')
              setIsFolderExpanded(false)
            }
          "
          :onTrashClick="
            () => {
              setCurrentFolder('trash')
              setIsFolderExpanded(false)
            }
          " />
      </div>
      <!-- 点击外部区域收起文件夹列表的覆盖层 -->
      <div v-if="isFolderExpanded" @click="() => setIsFolderExpanded(false)" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: transparent; z-index: 99"></div>

      <div style="padding: 0.8rem 0.5rem; margin-top: -2.8rem">
        <SearchBar v-model="searchQuery" @search="handleSearch" @clear="handleClearSearch" @focus="handleSearchFocus" @blur="handleSearchBlur" />
      </div>

      <div style="flex: 1">
        <div v-for="note in filteredAndSortedNotes" :key="note.id" style="margin: 0.4rem 0">
          <NoteItem 
              :title="note.title" 
              :content="note.content" 
              :date="formatDate(note.updatedAt)" 
              :isStarred="note.isStarred" 
              :isTop="note.isTop || false"
              :hasImage="note.hasImage || false"
              :onPress="() => handleNotePress(note.id)" 
              :onStarToggle="() => handleStarToggle(note.id)"
              :onTopToggle="() => handleTopToggle(note.id)"
              :onDelete="() => handleDeleteNote(note.id)"
            />
        </div>
      </div>
    </div>
    <ion-alert
      :is-open="showAlert"
      @didDismiss="() => setShowAlert(false)"
      header="删除便签"
      message="确定要删除这个便签吗？"
      :buttons="[
        {
          text: '取消',
          role: 'cancel',
        },
        {
          text: '删除',
          handler: confirmDeleteNote,
        },
      ]"></ion-alert>
  </ion-app>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../stores/useAppStore'
import { create, settings } from 'ionicons/icons'
import NoteItem from '../components/NoteItem.vue'
import Header from '../components/Header.vue'
import FolderManage from '../components/FolderManage.vue'
import SearchBar from '../components/SearchBar.vue'

const store = useAppStore()

// 加载初始数据
onMounted(() => {
  // 检查URL参数是否包含mock数据加载指令
  const urlParams = new URLSearchParams(window.location.search)
  if (urlParams.get('mock') === 'true') {
    store.loadMockData()
  } else {
    store.loadData()
  }
})

const searchQuery = ref('')
const sortBy = ref('date') // 'date', 'title', 'starred'
const isFolderExpanded = ref(false)
const currentFolder = ref('all') // 默认文件夹是"全部便签"
const showAlert = ref(false)
const noteToDelete = ref(null)

// 计算加星便签数量
const starredNotesCount = computed(() => {
  return store.notes.filter(note => note.isStarred).length
})

// 计算置顶便签数量
const topNotesCount = computed(() => {
  return filteredAndSortedNotes.value.filter(note => note.isTop).length
})

// 根据当前文件夹过滤便签
const filteredNotes = computed(() => {
  return store.notes.filter(note => {
    switch (currentFolder.value) {
      case 'all':
        return true
      case 'starred':
        return note.isStarred
      case 'trash':
        // 假设我们有一个isDeleted属性来标识已删除的便签
        return note.isDeleted || false
      default:
        return note.folderId === currentFolder.value
    }
  })
})

// Filter and sort notes
const filteredAndSortedNotes = computed(() => {
  return filteredNotes.value
    .filter(note => note.title.toLowerCase().includes(searchQuery.value.toLowerCase()) || note.content.toLowerCase().includes(searchQuery.value.toLowerCase()))
    .sort((a, b) => {
      // 置顶的便签排在前面
      if (a.isTop && !b.isTop) return -1
      if (!a.isTop && b.isTop) return 1

      if (sortBy.value === 'title') {
        return a.title.localeCompare(b.title)
      } else if (sortBy.value === 'starred') {
        return (b.isStarred ? 1 : 0) - (a.isStarred ? 1 : 0)
      } else {
        return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
      }
    })
})

// 计算头部标题
const headerTitle = computed(() => {
  switch (currentFolder.value) {
    case 'all':
      return '全部便签'
    case 'starred':
      return '加星便签'
    case 'trash':
      return '回收站'
    default:
      return '文件夹'
  }
})

const handleNotePress = noteId => {
  // 导航到详情页面的逻辑将在路由中处理
  window.location.hash = `#/notes/${noteId}`
}

const handleAddNote = () => {
  // 导航到编辑页面的逻辑将在路由中处理
  window.location.hash = '#/editor'
}

const handleDeleteNote = noteId => {
  noteToDelete.value = noteId
  showAlert.value = true
}

const handleStarToggle = async noteId => {
  const note = store.notes.find(n => n.id === noteId)
  if (note) {
    await store.updateNote(noteId, { isStarred: !note.isStarred })
  }
}

const handleTopToggle = async noteId => {
  const note = store.notes.find(n => n.id === noteId)
  if (note) {
    await store.updateNote(noteId, { isTop: !note.isTop })
  }
}

const confirmDeleteNote = () => {
  if (noteToDelete.value) {
    store.deleteNote(noteToDelete.value)
    noteToDelete.value = null
  }
  showAlert.value = false
}

const handleSort = () => {
  // In a full implementation, this would cycle through sort options
  const sortOptions = ['date', 'title', 'starred']
  const currentIndex = sortOptions.indexOf(sortBy.value)
  const nextIndex = (currentIndex + 1) % sortOptions.length
  sortBy.value = sortOptions[nextIndex]
  console.log('Sort by:', sortOptions[nextIndex])
}

const handleFolderPress = () => {
  // 导航到文件夹页面的逻辑将在路由中处理
  window.location.hash = '#/folders'
}

const handleSettingsPress = () => {
  // 导航到设置页面的逻辑将在路由中处理
  window.location.hash = '#/settings'
}

const handleFolderToggle = () => {
  // 在实际应用中，这里会触发文件夹列表的展开/收起
  isFolderExpanded.value = !isFolderExpanded.value
  console.log('Folder expanded:', !isFolderExpanded.value)
}

const handleSearch = query => {
  // 搜索功能已在computed属性filteredAndSortedNotes中实现
  console.log('Search for:', query)
}

const handleClearSearch = () => {
  // 清除搜索已在v-model中处理
  console.log('Search cleared')
}

const handleSearchFocus = () => {
  console.log('Search bar focused')
}

const handleSearchBlur = () => {
  console.log('Search bar blurred')
}

const formatDate = dateString => {
  return new Date(dateString).toLocaleDateString()
}

const setCurrentFolder = folder => {
  currentFolder.value = folder
}

const setIsFolderExpanded = expanded => {
  isFolderExpanded.value = expanded
}

const setSearchQuery = query => {
  searchQuery.value = query
}

const setShowAlert = show => {
  showAlert.value = show
}

const notes = computed(() => store.notes)
</script>
<style lang="less" scoped>
.container {
  width: 100vw;
  height: 100vh;
  background: url(/assets/icons/drawable-xxhdpi/note_background.png);
  background-size: cover;
}
</style>
