<template>
  <div class="min-h-screen bg-gray-50">
    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="bg-white rounded-lg shadow-lg p-6 sm:p-8">
        <!-- Profile Information Section -->
        <div class="mb-8">
          <div class="flex items-center space-x-4">
            <div class="relative">
              <img :src="userInfo.avatar" alt="User Avatar" 
                   class="w-24 h-24 rounded-full object-cover">
              <button @click="triggerFileInput" 
                      class="absolute bottom-0 right-0 bg-blue-500 text-white p-1 rounded-full">
                <i class="fas fa-camera"></i>
              </button>
              <input type="file" ref="fileInput" @change="handleAvatarChange" 
                     accept="image/*" class="hidden">
            </div>
            <div>
              <h2 class="text-2xl font-bold">{{ userInfo.username }}</h2>
              <p class="text-gray-600">{{ userInfo.bio }}</p>
            </div>
          </div>
        </div>

        <!-- Edit Profile Form -->
        <div v-if="isEditing" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700">Username</label>
            <input v-model="editForm.username" type="text" 
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">Bio</label>
            <textarea v-model="editForm.bio" rows="3" 
                      class="mt-1 block w-full rounded-md border-gray-300 shadow-sm"></textarea>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">Email</label>
            <input v-model="editForm.email" type="email" 
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
          </div>
          <div class="flex space-x-4">
            <button @click="saveProfile" 
                    class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600">
              Save
            </button>
            <button @click="cancelEdit" 
                    class="bg-gray-500 text-white px-4 py-2 rounded-md hover:bg-gray-600">
              Cancel
            </button>
          </div>
        </div>

        <!-- View Mode Button -->
        <button v-else @click="startEdit" 
                class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600">
          Edit Profile
        </button>

        <!-- My Posts List -->
        <div class="mt-8">
          <h3 class="text-xl font-bold mb-4">我的帖子</h3>
          <div v-if="loading" class="text-center py-4">
            <loading-spinner />
          </div>
          <div v-else-if="posts.length === 0" class="text-center text-gray-500 py-4">
            还没有发布过帖子
          </div>
          <div v-else class="space-y-4">
            <router-link 
              v-for="post in posts" 
              :key="post.id" 
              :to="'/article/' + post.id"
              class="block border rounded-lg p-4 hover:shadow-md transition bg-white"
            >
              <h4 class="text-lg font-semibold text-gray-900">{{ post.title }}</h4>
              <p class="text-sm text-gray-500 mt-1">
                发布于 {{ new Date(post.created_at).toLocaleString() }}
              </p>
              <p class="mt-2 text-gray-600 line-clamp-2">{{ post.summary }}</p>
              <div class="mt-2 flex space-x-4 text-sm text-gray-500">
                <span class="flex items-center">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                  </svg>
                  {{ post.views_count }}
                </span>
                <span class="flex items-center">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                  </svg>
                  {{ post.comments_count }}
                </span>
                <span class="flex items-center">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                  </svg>
                  {{ post.likes_count }}
                </span>
              </div>
            </router-link>
          </div>

          <!-- Pagination -->
          <div v-if="totalPages > 1" class="mt-6">
            <pagination 
              :current-page="currentPage"
              :total-pages="totalPages"
              @page-change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuth } from '../composables/useAuth'
import { useToast } from '../composables/useToast'
import { users, posts } from '../utils/api'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import Pagination from '../components/Pagination.vue'

export default {
  name: 'Profile',
  components: {
    LoadingSpinner,
    Pagination
  },
  setup() {
    const router = useRouter()
    const { user } = useAuth()
    const { showToast } = useToast()
    const fileInput = ref(null)

    // State
    const isEditing = ref(false)
    const loading = ref(false)
    const postsList = ref([])
    const currentPage = ref(1)
    const totalPages = ref(1)
    const pageSize = 10

    // Edit form
    const editForm = ref({
      username: user.value?.username || '',
      bio: user.value?.bio || '',
      email: user.value?.email || ''
    })

    // User info with computed default values
    const userInfo = ref({
      ...user.value,
      avatar: user.value?.avatar || '/default-avatar.png',
      bio: user.value?.bio || 'This user has not written a bio yet'
    })

    // Methods for profile editing
    const startEdit = () => {
      editForm.value = {
        username: userInfo.value.username,
        bio: userInfo.value.bio,
        email: userInfo.value.email
      }
      isEditing.value = true
    }

    const cancelEdit = () => {
      isEditing.value = false
      editForm.value = {
        username: userInfo.value.username,
        bio: userInfo.value.bio,
        email: userInfo.value.email
      }
    }

    const saveProfile = async () => {
      try {
        const { data } = await users.updateProfile(editForm.value)
        if (data) {
          userInfo.value = {
            ...userInfo.value,
            ...data
          }
          isEditing.value = false
          showToast('个人资料更新成功', 'success')
        }
      } catch (error) {
        showToast(error.response?.data?.detail || '更新个人资料失败', 'error')
      }
    }

    // Methods for avatar handling
    const triggerFileInput = () => {
      fileInput.value.click()
    }

    const handleAvatarChange = async (event) => {
      const file = event.target.files[0]
      if (!file) return

      if (!file.type.startsWith('image/')) {
        showToast('请选择图片文件', 'error')
        return
      }

      const formData = new FormData()
      formData.append('avatar', file)

      try {
        const { data } = await users.uploadAvatar(formData)
        if (data?.avatar) {
          userInfo.value.avatar = data.avatar
          showToast('头像更新成功', 'success')
        }
      } catch (error) {
        showToast(error.response?.data?.detail || '头像更新失败', 'error')
      }
    }

    // Methods for posts handling
    const fetchUserPosts = async (page = 1) => {
      loading.value = true
      try {
        const { data } = await posts.getUserPosts({ page, size: pageSize })
        postsList.value = data.items
        totalPages.value = data.pages
        currentPage.value = page
      } catch (error) {
        showToast(error.response?.data?.detail || '获取帖子失败', 'error')
      } finally {
        loading.value = false
      }
    }

    const handlePageChange = (page) => {
      fetchUserPosts(page)
    }

    // Lifecycle hooks
    onMounted(() => {
      fetchUserPosts(1)
    })

    return {
      userInfo,
      isEditing,
      editForm,
      loading,
      posts: postsList,
      currentPage,
      totalPages,
      fileInput,
      startEdit,
      cancelEdit,
      saveProfile,
      triggerFileInput,
      handleAvatarChange,
      handlePageChange
    }
  }
}
</script>
