<template>
  <ion-page>
    <div class="container">
      <Header :onBack="handleCancel" :onAction="handleAction" actionIcon="save" />

      <!-- 顶部信息栏 -->
      <div class="header-info">
        <span class="edit-time">{{ formattedTime }}</span>
        <span>|</span>
        <span class="word-count">{{ wordCount }}</span>
      </div>

      <!-- 富文本编辑器 -->
      <div class="editor-container">
        <RichTextEditor 
          ref="editorRef" 
          :modelValue="content" 
          @update:modelValue="handleContentChange"
          class="rich-text-editor" />
      </div>

      <ion-alert
        :is-open="showAlert"
        @didDismiss="() => setShowAlert(false)"
        header="未保存的更改"
        message="您有未保存的更改，确定要丢弃吗？"
        :buttons="[
          {
            text: '取消',
            role: 'cancel',
          },
          {
            text: '丢弃',
            handler: () => window.history.back(),
          },
        ]"></ion-alert>
    </div>
  </ion-page>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useAppStore } from '../stores/useAppStore'
import Header from '../components/Header.vue'
import RichTextEditor from '../components/RichTextEditor.vue'

const props = defineProps({
  id: {
    type: String,
    default: null,
  },
})

// 为了保持向后兼容性，我们也支持noteId属性
const noteId = computed(() => props.id || props.noteId)

const store = useAppStore()
const editorRef = ref(null)

// 设置便签内容的函数
const setNoteContent = async (noteId) => {
  // 确保store数据已加载
  if (store.notes.length === 0) {
    await store.loadData()
    console.log('Store loaded, notes count:', store.notes.length)
  }
  
  const note = store.notes.find(n => n.id === noteId)
  console.log('Found note:', note)
  
  // 确保编辑器已经初始化
  await nextTick()
  console.log('Editor ref:', editorRef.value)
  
  if (note) {
    console.log('Setting content:', note.content)
    // 无论editorRef是否可用，都先设置content的值
    content.value = note.content || ''
    // 如果editorRef可用，直接设置内容
    if (editorRef.value) {
      editorRef.value.setContent(note.content || '')
    }
  } else {
    console.log('Note not available')
  }
}

// 加载初始数据
onMounted(async () => {
  console.log('NoteEditorPage mounted')
  await store.loadData()
  console.log('Store loaded, notes count:', store.notes.length)
  
  // 如果是编辑现有便签，在组件挂载后设置内容
  if (noteId.value) {
    await setNoteContent(noteId.value)
  }
})

// 监听noteId变化，确保在编辑器准备好后设置内容
watch(noteId, async (newNoteId) => {
  console.log('Note ID changed:', newNoteId)
  if (newNoteId) {
    await setNoteContent(newNoteId)
  }
}, { immediate: true })

// 监听store变化，确保在store加载后设置内容
watch(() => store.notes, async (newNotes) => {
  if (noteId.value && newNotes.length > 0) {
    await setNoteContent(noteId.value)
  }
}, { immediate: true })

// Check if we're editing an existing note
const isEditing = !!noteId.value
const existingNote = isEditing ? store.notes.find(n => n.id === noteId.value) : null

// Initialize state with existing note data or empty strings
const content = ref(existingNote?.content || '')

// 当组件挂载时，确保编辑器初始化为空内容（针对新建便签）
onMounted(() => {
  if (!isEditing && editorRef.value) {
    console.log('Initializing editor for new note')
    editorRef.value.setContent('')
  }
})

// 监听store变化，确保在store加载后设置内容
watch(() => store.notes, async (newNotes) => {
  if (noteId.value && newNotes.length > 0) {
    await setNoteContent(noteId.value)
  }
}, { immediate: true })
const showAlert = ref(false)

// 防抖函数
const debounce = (func, delay) => {
  let timeoutId
  return function (...args) {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(this, args), delay)
  }
}

// 防抖处理内容变化
const debouncedHandleContentChange = debounce((newContent) => {
  content.value = newContent
  console.log('Content updated:', newContent)
}, 300)

// 监听编辑器内容变化
const handleContentChange = (newContent) => {
  console.log('Editor content changed:', newContent)
  debouncedHandleContentChange(newContent)
}

// 计算属性
const formattedTime = computed(() => {
  const now = new Date()
  const date = existingNote?.updatedAt ? new Date(existingNote.updatedAt) : now

  // 如果是今天
  if (date.toDateString() === now.toDateString()) {
    return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }

  // 如果是昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }

  // 其他情况显示月日
  return `${date.getMonth() + 1}月${date.getDate()}日`
})

const wordCount = computed(() => {
  // 移除HTML标签计算字数
  const textContent = content.value.replace(/<[^>]*>/g, '')
  return textContent.length || 0
})

// 处理保存
const handleSave = async () => {
  try {
    // 获取编辑器中的实际内容
    const editorContent = editorRef.value ? editorRef.value.getContent() : content.value
    
    if (isEditing && existingNote) {
      // Update existing note
      await store.updateNote(noteId.value, {
        content: editorContent,
      })
    } else {
      // Create new note
      await store.addNote({
        content: editorContent,
        isStarred: false,
      })
    }

    // Navigate back to the previous screen
    window.location.hash = '#/notes'
  } catch (error) {
    // In a full implementation, show an alert or toast
    console.log('Save error: Failed to save note. Please try again.')
  }
}

// 处理取消
const handleCancel = () => {
  // Check if there are unsaved changes
  const hasUnsavedChanges = content.value !== (existingNote?.content || '')

  if (hasUnsavedChanges) {
    showAlert.value = true
  } else {
    window.location.hash = '#/notes'
  }
}

// 处理创建（用于新建便签）
const handleCreate = async () => {
  try {
    // 获取编辑器中的实际内容
    const editorContent = editorRef.value ? editorRef.value.getContent() : content.value
    
    // Create new note
    await store.addNote({
      content: editorContent,
      isStarred: false,
    })

    // Navigate back to the previous screen
    window.location.hash = '#/notes'
  } catch (error) {
    // In a full implementation, show an alert or toast
    console.log('Create error: Failed to create note. Please try again.')
  }
}

// 处理Header组件的操作按钮点击事件
const handleAction = actionType => {
  if (actionType === 'save') {
    handleSave()
  } else if (actionType === 'create') {
    handleCreate()
  } else if (actionType === 'insertImage') {
    // 插入图片功能
    if (editorRef.value) {
      // 通过editorRef调用RichTextEditor组件的方法来插入图片
      editorRef.value.insertImage()
    }
  }
}

const setShowAlert = value => {
  showAlert.value = value
}
</script>

<style lang="less" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background);
}

.editor-container {
  flex: 1;
  overflow-y: auto;
  background-color: var(--background-card);
}

.rich-text-editor {
  height: 100%;
}

.header-info {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
  padding: 1.5rem 16px 0.7rem 16px;
  background-color: var(--background-card);
  border-bottom: 1px solid var(--border);
  font-size: 0.7rem;
  color: var(--text-tertiary);
}
</style>
