import { defineStore } from 'pinia'
import * as storage from '../utils/storage'

export const useAppStore = defineStore('app', {
  state: () => ({
    notes: [],
    folders: [],
    settings: { cloudSync: false, darkMode: false },
  }),

  getters: {
    starredNotesCount: state => {
      return state.notes.filter(note => note.isStarred).length
    },

    allNotesCount: state => {
      return state.notes.length
    },
  },

  actions: {
    // 初始化数据
    async loadData() {
      try {
        const loadedNotes = await storage.getNotes()
        const loadedFolders = await storage.getFolders()
        const loadedSettings = await storage.getSettings()

        // 如果没有数据，则加载mock数据
        if (loadedNotes.length === 0 && loadedFolders.length === 0) {
          this.loadMockData()
        } else {
          this.notes = loadedNotes
          this.folders = loadedFolders
          this.settings = loadedSettings
        }
      } catch (error) {
        console.error('Error loading data:', error)
      }
    },

    // 加载mock数据
    async loadMockData() {
      // Mock notes
      const mockNotes = [
        {
          id: '1',
          title: '欢迎使用锤子便签',
          content: '这是一个功能强大的便签应用，您可以在这里记录您的想法、待办事项等。',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          folderId: null,
          isStarred: true,
          isTop: true,
          hasImage: false,
          isDeleted: false,
          deletedAt: null,
        },
        {
          id: '2',
          title: '待办事项',
          content: '1. 完成项目报告\n2. 购买 groceries\n3. 预约医生\n4. 给朋友打电话',
          createdAt: new Date(Date.now() - 86400000).toISOString(), // 昨天
          updatedAt: new Date(Date.now() - 86400000).toISOString(),
          folderId: null,
          isStarred: true,
          isTop: false,
          hasImage: true,
          isDeleted: false,
          deletedAt: null,
        },
        {
          id: '3',
          title: '购物清单',
          content: '苹果\n牛奶\n面包\n鸡蛋\n西红柿\n咖啡',
          createdAt: new Date(Date.now() - 172800000).toISOString(), // 前天
          updatedAt: new Date(Date.now() - 172800000).toISOString(),
          folderId: null,
          isStarred: false,
          isTop: false,
          hasImage: false,
          isDeleted: false,
          deletedAt: null,
        },
        {
          id: '4',
          title: '项目想法',
          content: '1. 实现云同步功能\n2. 添加深色模式\n3. 支持Markdown语法\n4. 添加标签功能',
          createdAt: new Date(Date.now() - 259200000).toISOString(), // 3天前
          updatedAt: new Date(Date.now() - 259200000).toISOString(),
          folderId: null,
          isStarred: false,
          isTop: false,
          hasImage: false,
          isDeleted: false,
          deletedAt: null,
        },
        {
          id: '5',
          title: '读书笔记',
          content: '《Vue.js实战》\n- 组件化思想是Vue的核心\n- 理解响应式原理很重要\n- Pinia是Vue 3的推荐状态管理库',
          createdAt: new Date(Date.now() - 345600000).toISOString(), // 4天前
          updatedAt: new Date(Date.now() - 345600000).toISOString(),
          folderId: null,
          isStarred: false,
          isTop: false,
          hasImage: false,
          isDeleted: false,
          deletedAt: null,
        },
        {
          id: '6',
          title: '已删除的便签',
          content: '这是一条已删除的便签示例，应该只在回收站中显示。',
          createdAt: new Date(Date.now() - 432000000).toISOString(), // 5天前
          updatedAt: new Date(Date.now() - 432000000).toISOString(),
          folderId: null,
          isStarred: false,
          isTop: false,
          hasImage: false,
          isDeleted: true,
          deletedAt: new Date(Date.now() - 86400000).toISOString(), // 1天前删除
        },
      ]

      // Mock folders
      const mockFolders = [
        {
          id: 'folder1',
          name: '工作',
          createdAt: new Date().toISOString(),
        },
        {
          id: 'folder2',
          name: '个人',
          createdAt: new Date().toISOString(),
        },
        {
          id: 'folder3',
          name: '学习',
          createdAt: new Date().toISOString(),
        },
      ]

      // Mock settings
      const mockSettings = {
        cloudSync: false,
        darkMode: false,
      }

      this.notes = mockNotes
      this.folders = mockFolders
      this.settings = mockSettings

      // 保存到localStorage
      await storage.saveNotes(mockNotes)
      await storage.saveFolders(mockFolders)
      await storage.saveSettings(mockSettings)
    },

    // 保存notes到localStorage
    async saveNotes() {
      try {
        await storage.saveNotes(this.notes)
      } catch (error) {
        console.error('Error saving notes:', error)
      }
    },

    // 保存folders到localStorage
    async saveFolders() {
      try {
        await storage.saveFolders(this.folders)
      } catch (error) {
        console.error('Error saving folders:', error)
      }
    },

    // 保存settings到localStorage
    async saveSettings() {
      try {
        await storage.saveSettings(this.settings)
      } catch (error) {
        console.error('Error saving settings:', error)
      }
    },

    // Note functions
    async addNote(note) {
      try {
        const newNote = await storage.addNote(note)
        this.notes.push(newNote)
        return newNote
      } catch (error) {
        console.error('Error adding note:', error)
        throw error
      }
    },

    async updateNote(id, updates) {
      try {
        const updatedNote = await storage.updateNote(id, updates)
        if (updatedNote) {
          const index = this.notes.findIndex(note => note.id === id)
          if (index !== -1) {
            this.notes[index] = updatedNote
          }
        }
        return updatedNote
      } catch (error) {
        console.error('Error updating note:', error)
        throw error
      }
    },

    async deleteNote(id) {
      try {
        const result = await storage.deleteNote(id)
        if (result) {
          this.notes = this.notes.filter(note => note.id !== id)
        }
        return result
      } catch (error) {
        console.error('Error deleting note:', error)
        throw error
      }
    },

    // 将便签移至回收站
    async moveToTrash(id) {
      try {
        const updatedNote = await storage.updateNote(id, { isDeleted: true, deletedAt: new Date().toISOString() })
        if (updatedNote) {
          const index = this.notes.findIndex(note => note.id === id)
          if (index !== -1) {
            this.notes[index] = updatedNote
          }
        }
        return updatedNote
      } catch (error) {
        console.error('Error moving note to trash:', error)
        throw error
      }
    },

    // 永久删除便签
    async permanentlyDeleteNote(id) {
      try {
        const result = await storage.deleteNote(id)
        if (result) {
          this.notes = this.notes.filter(note => note.id !== id)
        }
        return result
      } catch (error) {
        console.error('Error permanently deleting note:', error)
        throw error
      }
    },

    // Folder functions
    async addFolder(folder) {
      try {
        const newFolder = await storage.addFolder(folder)
        this.folders.push(newFolder)
        return newFolder
      } catch (error) {
        console.error('Error adding folder:', error)
        throw error
      }
    },

    // Settings functions
    async updateSettings(newSettings) {
      try {
        const updatedSettings = { ...this.settings, ...newSettings }
        this.settings = updatedSettings
        await storage.saveSettings(updatedSettings)
      } catch (error) {
        console.error('Error updating settings:', error)
        throw error
      }
    },

    // 切换云同步设置
    async toggleCloudSync() {
      await this.updateSettings({ cloudSync: !this.settings.cloudSync })
    },

    // 切换深色模式设置
    async toggleDarkMode() {
      await this.updateSettings({ darkMode: !this.settings.darkMode })
    },
  },
})
