<template>
  <div class="home">
    <div class="intro">
      <h1 style="color:white;">Formula 1</h1>
      <p style="color:white;">赛事与社区评论</p>
    </div>
    <div class="content">
      <div class="section">
        <h2 style="color:white;">已完成赛事</h2>
        <div class="grid">
          <el-card v-for="race in upcomingRaces" :key="race.id" class="race-card" shadow="hover">
            <div class="race-header">
              <span class="race-round">Round {{ race.round }}</span>
              <span class="race-date">{{ race.date }}</span>
            </div>
            <div class="race-title">{{ race.name }}</div>
            <div class="race-meta">赛道：{{ race.circuit }} · 城市：{{ race.city }}</div>
            <div class="race-actions">
              <el-button type="primary" size="small" @click="goDetail(race.season, race.id)">查看详情</el-button>
            </div>
          </el-card>
        </div>
      </div>
      <div class="section">
        <h2 style="color:white;">最新评论</h2>
        <div class="comments">
          <el-card v-for="c in pageComments[page - 1]" :key="c.id" class="comment-card" shadow="never">
            <div class="comment-header">
              <div class="user-info">
                <el-avatar :size="32">{{ c.username?.[0] || '?' }}</el-avatar>
                <div class="comment-user">{{ c.username }}</div>
              </div>
              <!-- <div class="comment-time">{{ c.time }}</div> -->
              <el-button v-if="c.user_id === user_id" type="danger" class="delete" @click="deleteComment(c.id)"><el-icon>
                  <Delete />
                </el-icon></el-button>
            </div>
            <div class="comment-content">{{ c.content }}</div>
            <div class="comment-actions">
              <el-button size="small" @click="replyComment(c)">回复</el-button>
              <el-button size="small" type="primary" @click="viewDetail(c)">查看详情</el-button>
            </div>
          </el-card>
        </div>
        <div class="comment-pagination">
          <el-button :disabled="page === 1" @click="prevPage">上一页</el-button>
          <span class="page-info">第 {{ page }} / {{ totalPages }} 页</span>
          <el-button :disabled="page >= totalPages" @click="nextPage">下一页</el-button>
        </div>
        <div class="comment-compose">
          <el-input v-model="compose" type="textarea" :rows="3" placeholder="发表你的评论..." />
          <div class="compose-actions">
            <el-button type="primary" :loading="posting" @click="postNewComment">发表</el-button>
          </div>
        </div>
        <el-dialog v-model="replyVisible" title="回复评论" width="500px">
          <div class="reply-target">回复：{{ replyTarget?.content }}</div>
          <el-input v-model="replyText" type="textarea" :rows="3" placeholder="输入你的回复..." />
          <template #footer>
            <el-button @click="replyVisible = false">取消</el-button>
            <el-button type="primary" :loading="replyPosting" @click="submitReply">发表回复</el-button>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>

</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fetchLatestComments, postComment, postReply, type CommentItem } from '@/api/comments'
import { isAuthenticated } from '@/utils/auth'
import { userInfoStore } from '@/store/UserInfo'

const upcomingRaces = ref([
  { id: 1, round: 1, name: '澳大利亚大奖赛', circuit: 'Albert Park Circuit', city: 'Melbourne', date: '2025-03-09', season: 2025, has_sprint: false },
  { id: 2, round: 2, name: '中国大奖赛', circuit: 'Shanghai International Circuit', city: 'Shanghai', date: '2025-04-20', season: 2025, has_sprint: true },
  { id: 3, round: 3, name: '日本大奖赛', circuit: 'Suzuka International Racing Course', city: 'Mie Prefecture', date: '2025-04-06', season: 2025, has_sprint: false },
  { id: 4, round: 4, name: '巴林大奖赛', circuit: 'Bahrain International Circuit', city: 'Sakhir', date: '2025-03-23', season: 2025, has_sprint: false },
])

const userInfo = userInfoStore()
const user_id = ref(0)


const allComments = ref<any>([])
const page = ref(1)
const pageSize = ref(5)
const total = ref(0)
const totalPages = computed(() => Math.max(1, Math.ceil(Math.min(100, total.value) / pageSize.value)))
const pageComments = computed(() => allComments.value)

const loadComments = async () => {
  try {
    const data = await fetch(`/api/comments?limit=100&offset=0&pageSize=${pageSize.value}`)
    const json = await data.json()
    allComments.value = Array.isArray(json) ? json : (json?.data ?? [])

    total.value = 0
    for (const c of allComments.value) {
      total.value += c.length
    }
    await userInfo.ensureUserInfoLoaded()
    console.log(userInfo.userInfo)
    user_id.value = userInfo.userInfo.id
    console.log(user_id.value)
  } catch (e: any) {
    console.log(e)
    //后端未就绪可使用占位数据
    allComments.value = [
      { id: 1, username: 'Alex', content: '期待新赛季的轮胎策略变化。', user_id: 1 },
      { id: 2, username: 'Mia', content: '澳洲站的升级包会是关键。', user_id: 2 },
      { id: 3, username: 'Ken', content: '维斯塔潘和诺里斯的较量值得期待。', user_id: 3 }
    ]
    total.value = allComments.value.length
  }
}

onMounted(loadComments)

const prevPage = async () => {
  if (page.value === 1) return
  page.value -= 1
  await loadComments()
}
const nextPage = async () => {
  if (page.value >= totalPages.value) return
  page.value += 1
  await loadComments()
}

const compose = ref('')
const posting = ref(false)
const postNewComment = async () => {
  if (!isAuthenticated()) {
    ElMessage.warning('请先登录后再发表评论')
    return
  }
  if (!compose.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  posting.value = true
  try {
    await postComment(user_id.value, compose.value.trim())
    ElMessage.success('发表成功')
    compose.value = ''
    await loadComments()
  } catch (e: any) {
    ElMessage.error(e?.message || '发表失败')
  } finally {
    posting.value = false
  }
}

const replyVisible = ref(false)
const replyTarget = ref<CommentItem | null>(null)
const replyText = ref('')
const replyPosting = ref(false)
const replyComment = (c: CommentItem) => {
  if (!isAuthenticated()) {
    ElMessage.warning('请先登录后再回复')
    return
  }
  replyTarget.value = c
  replyText.value = ''
  replyVisible.value = true
}
const submitReply = async () => {
  if (!replyTarget.value) return
  if (!replyText.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  replyPosting.value = true
  try {
    await postReply(replyTarget.value.id, replyText.value.trim(), user_id.value)
    ElMessage.success('回复已发表')
    replyVisible.value = false
  } catch (e: any) {
    ElMessage.error(e?.message || '回复失败')
  } finally {
    replyPosting.value = false
  }
}

const deleteComment = async (id: number) => {
  if (!isAuthenticated()) {
    ElMessage.warning('请先登录后再删除评论')
    return
  }
  try {
    await ElMessageBox.confirm('确定删除该评论？删除后不可恢复', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch {
    return
  }
  try {
    await fetch(`/api/comments/${id}`, { method: 'DELETE', credentials: 'include' })
    ElMessage.success('删除成功')
    await loadComments()
  } catch (e: any) {
    ElMessage.error(e?.message || '删除失败')
  }
}

const router = useRouter()

const goDetail = (season: number, id: number) => {
  router.push(`/seasons/${season}/races/${id}`)
}

const viewDetail = (c: CommentItem) => {
  router.push({ name: 'comment-detail', params: { id: c.id } })
}
</script>

<style scoped lang="scss">
.home {
  padding: 20px;
}

.intro h1 {
  font-size: 40px;
  font-weight: bolder;
}

.intro p {
  font-size: 20px;
  margin-bottom: 20px;
}

.content {
  display: grid;
  grid-template-columns: 1fr;
  row-gap: 30px;
}

.section h2 {
  font-size: 28px;
  margin-bottom: 10px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.race-card {
  border-radius: 10px;
}

.race-header {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
}

.race-title {
  font-size: 20px;
  font-weight: 600;
  margin: 6px 0;
}

.race-meta {
  font-size: 14px;
  color: #888;
}

.race-actions {
  margin-top: 10px;
}

.comments {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}

.comment-card {
  border-radius: 10px;
}

.comment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.comment-user {
  font-weight: 600;
}

.comment-time {
  margin-left: auto;
  font-size: 12px;
  color: #888;
}

.delete {}

.comment-content {
  margin-top: 8px;
  font-size: 14px;
}

.comment-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.comment-pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}

.page-info {
  color: #666;
}

.comment-compose {
  margin-top: 16px;
  display: grid;
  grid-template-columns: 1fr;
  gap: 10px;
}

.compose-actions {
  text-align: right;
}
</style>
