<template>
  <div class="bg-light-gray font-sans text-text-dark flex flex-col h-screen antialiased">
    <!-- Header -->
    <header class="bg-white shadow-md z-10 flex-shrink-0">
      <div class="container mx-auto px-4 py-3 flex items-center justify-between relative">
        <div class="flex items-center space-x-4">
          <router-link to="/" class="text-text-medium hover:text-tech-blue transition-colors">
            <i data-lucide="home" class="w-6 h-6"></i>
          </router-link>
          <router-link to="/messages" class="text-text-medium hover:text-tech-blue transition-colors">
            <i data-lucide="bell" class="w-6 h-6"></i>
          </router-link>
        </div>
        <h1 class="text-lg font-bold text-text-dark absolute left-1/2 -translate-x-1/2">日记</h1>
        <router-link to="/settings" class="text-text-medium hover:text-tech-blue transition-colors">
          <i data-lucide="user" class="w-6 h-6"></i>
        </router-link>
      </div>
    </header>

    <!-- Main Content -->
    <main class="flex-1 overflow-y-auto p-4 lg:p-6 pb-24">
      <!-- New Post Form -->
      <div id="new-post-section" class="bg-white p-4 rounded-xl shadow-sm mb-6 scroll-mt-20">
        <h2 class="font-bold text-text-dark mb-3">发布新日记</h2>
        <textarea
          id="new-diary-content"
          v-model="newDiaryContent"
          class="w-full h-24 p-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-tech-blue/50 focus:border-tech-blue outline-none transition"
          placeholder="今天有什么新鲜事或心里话想对开开说？"
        ></textarea>
        <div class="mt-3 flex justify-end">
          <button
            @click="publishDiaryHandler"
            :disabled="publishDisabled"
            class="bg-tech-blue text-white px-5 py-2 rounded-full font-semibold hover:bg-blue-600 transition-all duration-300 transform hover:scale-105 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
          >
            发布
          </button>
        </div>
      </div>

      <!-- Diary Feed -->
      <div id="diary-feed" class="space-y-4">
        <!-- 加载状态 -->
        <div v-if="loading" class="text-center py-12">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-tech-blue"></div>
          <p class="mt-2 text-text-medium">加载中...</p>
        </div>
        
        <!-- 空状态 -->
        <div v-else-if="diaries.length === 0" class="text-center py-12">
          <i data-lucide="book-open" class="w-16 h-16 text-gray-300 mx-auto mb-4"></i>
          <p class="text-text-medium text-lg mb-2">还没有日记</p>
          <p class="text-text-medium text-sm">写下你的第一篇日记，开开会给你温暖的回应</p>
        </div>
        
        <!-- 日记列表 -->
        <div
          v-for="entry in diaries"
          :key="entry.id"
          class="bg-white rounded-xl shadow-sm p-4 animate-fade-in-up"
        >
          <!-- 用户日记内容 -->
          <div class="flex items-center mb-4">
            <i
              data-lucide="user-circle-2"
              class="w-10 h-10 text-gray-400"
            ></i>
            <div class="ml-3">
              <p class="font-semibold text-text-dark">我</p>
              <p class="text-xs text-text-medium">{{ formatTime(entry.publishTime) }}</p>
            </div>
          </div>

          <p class="text-text-dark whitespace-pre-wrap leading-relaxed">{{ entry.content }}</p>

          <!-- AI评论 -->
          <div v-if="entry.aiComment" class="mt-4 pt-3 border-t border-gray-100">
            <div class="flex items-start">
              <img
                src="https://r2.flowith.net/files/o/1752574572161-kaikai_character_energetic_animation_index_2@1024x1024.png"
                alt="开开"
                class="w-8 h-8 rounded-full object-cover flex-shrink-0"
              >
              <div class="ml-3 bg-light-gray p-3 rounded-lg w-full">
                <p class="text-sm font-semibold text-text-dark">开开</p>
                <p class="text-sm text-text-dark mt-1">{{ entry.aiComment }}</p>
                <p class="text-xs text-text-medium mt-2">{{ formatTime(entry.aiCommentTime) }}</p>
              </div>
            </div>
          </div>

          <!-- 互动按钮 -->
          <div class="mt-4 pt-3 border-t border-gray-100 flex items-center justify-between">
            <div class="flex items-center space-x-4">
              <button class="flex items-center text-sm text-text-medium hover:text-tech-blue transition-colors">
                <i data-lucide="heart" class="w-4 h-4 mr-1.5"></i>
                <span>{{ entry.likeCount || 0 }}</span>
              </button>
              <button class="flex items-center text-sm text-text-medium hover:text-tech-blue transition-colors">
                <i data-lucide="message-square" class="w-4 h-4 mr-1.5"></i>
                <span>{{ entry.commentCount || 0 }}</span>
              </button>
              <button class="flex items-center text-sm text-text-medium hover:text-tech-blue transition-colors">
                <i data-lucide="eye" class="w-4 h-4 mr-1.5"></i>
                <span>{{ entry.viewCount || 0 }}</span>
              </button>
            </div>
            <button class="flex items-center text-sm text-text-medium hover:text-tech-blue transition-colors">
              <i data-lucide="share" class="w-4 h-4 mr-1.5"></i>
              <span>分享</span>
            </button>
          </div>
        </div>
      </div>
      <div class="flex justify-center mt-6">
        <el-pagination
          v-if="total > pageSize"
          v-model:current-page="page"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="total"
          @current-change="onPageChange"
        />
      </div>
    </main>

    <!-- App Navigation -->
    <BottomNavigation />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import BottomNavigation from '@/components/layout/BottomNavigation.vue'
import { publishDiary, getUserDiaries } from '@/services/diary'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

const authStore = useAuthStore()
const userId = authStore.userId

const newDiaryContent = ref('')
const publishDisabled = ref(false)
const loading = ref(false)
const diaries = ref<any[]>([])
const page = ref(1)
const pageSize = 10
const total = ref(0)

const fetchDiaries = async () => {
  if (!userId) return
  console.log('🔍 开始获取日记数据，用户ID:', userId)
  loading.value = true
  try {
    const res = await getUserDiaries(userId, page.value, pageSize)
    console.log('🔍 API返回的日记数据:', res)
    if (res?.data?.records) {
      diaries.value = res.data.records
      total.value = res.data.total
      console.log('🔍 设置日记数据:', diaries.value)
    } else {
      console.log('🔍 API返回数据格式不正确:', res)
    }
  } catch (error) {
    console.error('🔍 获取日记数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 格式化时间显示
const formatTime = (timeStr: string) => {
  if (!timeStr) return ''
  try {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.error('格式化时间失败:', error)
    return timeStr
  }
}

const publishDiaryHandler = async () => {
  const content = newDiaryContent.value.trim()
  if (!content) return
  publishDisabled.value = true
  try {
    await publishDiary({
      userId,
      title: '',
      content,
      images: [],
      videos: [],
      location: '',
      weather: '',
      mood: '',
      moodScore: null,
      tags: [],
      isPublic: 1,
      isAnonymous: 0
    })
    ElMessage.success('发布成功')
    newDiaryContent.value = ''
    fetchDiaries()
  } finally {
    setTimeout(() => { publishDisabled.value = false }, 2000)
  }
}

const onPageChange = (val: number) => {
  page.value = val
  fetchDiaries()
}

onMounted(fetchDiaries)

// 生命周期
onMounted(() => {
  // 初始化Lucide图标
  if (window.lucide) {
    window.lucide.createIcons()
  }

  // 延迟初始化图标
  setTimeout(() => {
    if (window.lucide) {
      window.lucide.createIcons()
    }
  }, 100)
})
</script>

<style scoped>
/* 导入原始样式变量 */
:root {
  --tech-blue: #4A90E2;
  --warm-orange: #F5A623;
  --white: #FFFFFF;
  --light-gray: #F7F8FA;
  --text-dark: #333333;
  --text-medium: #888888;
}

/* 应用原始样式类 */
.bg-tech-blue { background-color: var(--tech-blue); }
.bg-warm-orange { background-color: var(--warm-orange); }
.bg-light-gray { background-color: var(--light-gray); }
.text-tech-blue { color: var(--tech-blue); }
.text-text-dark { color: var(--text-dark); }
.text-text-medium { color: var(--text-medium); }
.border-tech-blue { border-color: var(--tech-blue); }

.animate-fade-in-up {
  animation: fade-in-up 0.8s ease-out forwards;
  opacity: 0;
}

@keyframes fade-in-up {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 全局样式 */
body {
  font-family: 'Noto Sans SC', sans-serif;
}
</style>