<template>
  <div class="make-wish-page">
    <van-nav-bar title="许下心愿" left-text="返回" left-arrow @click-left="$router.back()" />

    <div class="page-body">
      <div class="tree-info" v-if="tree">
        <p class="for-tree">🌳 {{ tree.name }}</p>
        <van-tag v-if="tree.distance != null" :type="isInRange ? 'success' : 'warning'" round>
          {{ isInRange ? `距离 ${fmtDist(tree.distance)} · 在范围内` : `距离 ${fmtDist(tree.distance)} · 太远了` }}
        </van-tag>
      </div>

      <!-- 图片上传 -->
      <div class="section">
        <h4 class="section-title">心愿照片（可选）</h4>
        <image-uploader v-model="images" :max="9" />
      </div>

      <!-- 愿望内容 -->
      <div class="section">
        <h4 class="section-title">写下你的愿望</h4>
        <van-field
          v-model="content"
          type="textarea"
          rows="4"
          :maxlength="200"
          :show-word-limit="true"
          placeholder="希望家人身体健康，工作顺利..."
        />
      </div>

      <!-- 标签选择 -->
      <div class="section">
        <h4 class="section-title">选择标签（可选）</h4>
        <tag-selector v-model="tags" />
      </div>

      <!-- 公开设置 -->
      <div class="section">
        <van-cell title="公开愿望" :value="isPublic ? '他人可见' : '仅自己可见'">
          <template #right-icon>
            <van-switch v-model="isPublic" size="22" />
          </template>
        </van-cell>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <van-button
          type="primary"
          block
          round
          :loading="submitting"
          :disabled="!content.trim() || !isInRange"
          @click="submitWish"
        >
          {{ isInRange ? '🙏 许愿' : '需要靠近许愿树才能许愿' }}
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showSuccessToast } from 'vant'
import { useLocationStore } from '@/stores/location'
import { useUserStore } from '@/stores/user'
import { fetchTreeDetail } from '@/api/tree'
import { submitWish as submitWishApi } from '@/api/wish'
import ImageUploader from '@/components/ImageUploader.vue'
import TagSelector from '@/components/TagSelector.vue'

const route = useRoute()
const router = useRouter()
const locationStore = useLocationStore()
const userStore = useUserStore()

const tree = ref<any>(null)
const images = ref<string[]>([])
const content = ref('')
const tags = ref<string[]>([])
const isPublic = ref(true)
const submitting = ref(false)

function fmtDist(m: number) {
  return m >= 1000 ? (m / 1000).toFixed(1) + 'km' : m + 'm'
}

const isInRange = computed(() => tree.value?.isInRange ?? false)

async function submitWish() {
  if (!content.value.trim()) {
    showToast('请写下你的愿望')
    return
  }
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    router.push('/login')
    return
  }

  submitting.value = true
  try {
    await submitWishApi({
      treeId: tree.value.id,
      content: content.value,
      images: images.value,
      lng: locationStore.lng || 0,
      lat: locationStore.lat || 0,
      address: tree.value.address,
      isPublic: isPublic.value,
      tags: tags.value,
      type: 1,
    })
    showSuccessToast('愿望已挂在树上！祝你心想事成 ✨')
    setTimeout(() => router.replace('/my-wishes'), 2200)
  } finally {
    submitting.value = false
  }
}

onMounted(async () => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    router.replace('/login')
    return
  }
  const id = Number(route.query.treeId)
  if (id) {
    if (!locationStore.located) {
      await locationStore.refreshLocation()
    }
    tree.value = await fetchTreeDetail(id, locationStore.lng ?? undefined, locationStore.lat ?? undefined)
  }
})
</script>

<style scoped>
.make-wish-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 30px;
}
.page-body {
  padding: 12px;
}
.tree-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
}
.for-tree {
  font-size: 15px;
  font-weight: 500;
}
.section {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 12px;
}
.section-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}
.submit-section {
  padding: 20px 16px;
}
</style>
