<template>
  <ion-page>
    <div class="container">
      <Header :title="isEditing ? '编辑便签' : '新建便签'" :onBack="handleCancel" :onAction="handleSave" actionText="保存" />

      <!-- 标题输入框 -->
      <div class="title-input-container">
        <input placeholder="标题" v-model="title" class="title-input" />
      </div>

      <!-- 富文本编辑器 -->
      <div class="editor-container">
        <RichTextEditor ref="editorRef" v-model="content" class="rich-text-editor" />
      </div>

      <!-- 底部信息栏 -->
      <div class="footer-info">
        <span class="edit-time">{{ formattedTime }}</span>
        <span class="word-count">{{ wordCount }} 字</span>
      </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 } from 'vue'
import { useAppStore } from '../stores/useAppStore'
import Header from '../components/Header.vue'
import RichTextEditor from '../components/RichTextEditor.vue'

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

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

// 加载初始数据
onMounted(async () => {
  await store.loadData()
})

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

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

// 计算属性
const formattedTime = computed(() => {
  if (!isEditing) return '新建便签'

  const date = new Date(existingNote.updatedAt)
  const now = new Date()

  // 如果是今天
  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 (title.value.length || 0) + (textContent.length || 0)
})

// 处理保存
const handleSave = async () => {
  // Validate input
  if (!title.value.trim()) {
    // In a full implementation, show an alert or toast
    console.log('Validation error: Please enter a note title.')
    return
  }

  try {
    if (isEditing && existingNote) {
      // Update existing note
      await store.updateNote(props.noteId, {
        title: title.value,
        content: content.value,
      })
    } else {
      // Create new note
      await store.addNote({
        title: title.value,
        content: content.value,
        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 = title.value !== (existingNote?.title || '') || content.value !== (existingNote?.content || '')

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



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

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

.toolbar {
  display: flex;
  padding: 8px 16px;
  border-bottom: 1px solid var(--border);
  background-color: var(--background-card);
}

.toolbar-btn {
  padding: 8px;
  margin-right: 8px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 4px;
}

.toolbar-btn:hover {
  background-color: var(--background-hover);
}

.toolbar-icon {
  width: 24px;
  height: 24px;
}

.title-input-container {
  padding: 16px;
  border-bottom: 1px solid var(--border);
  background-color: var(--background-card);
}

.title-input {
  width: 100%;
  font-size: 22px;
  font-weight: 600;
  color: var(--note-title);
  background-color: transparent;
  border: none;
  outline: none;
  padding: 0;
}

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

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

.footer-info {
  display: flex;
  justify-content: space-between;
  padding: 8px 16px;
  background-color: var(--background-card);
  border-top: 1px solid var(--border);
  font-size: 14px;
  color: var(--text-tertiary);
}
</style>
