<template>
  <view class="available-page">
    <UnauthLoginPanel
      v-if="!session.isLoggedIn"
      @login="login"
    />

    <block v-else>
      <view class="session-list">
        <view v-for="session in sessions" :key="session.id" class="card session-card" @tap="onSessionTap(session)">
          <image :src="session.cover_image" mode="aspectFill" class="session-cover" />
          <view class="session-info">
            <view class="session-top">
              <text class="session-title">{{ session.title }}</text>
            </view>
            <text class="time-line">{{ formatTimeRange(session.start_at, session.end_at) }}</text>
            <text class="meta">{{ session.coach_name }}</text>
            <view class="session-bottom">
              <text class="meta">剩余 {{ session.remaining_count }}/{{ session.capacity }}</text>
              <text class="session-price">¥{{ session.price }}</text>
            </view>
          </view>
        </view>

        <view v-if="isLoading" class="load-more-tip">加载中...</view>
        <view v-else-if="sessions.length === 0" class="empty-state">暂无可约课程</view>
        <view v-else-if="!hasMore" class="load-more-tip">已加载全部</view>
        <view v-if="isLoadingMore" class="load-more-tip">加载中...</view>
      </view>

      <view v-if="cardPickerVisible" class="picker-mask" @tap="closeCardPicker">
        <view class="picker-sheet" @tap.stop>
          <text class="picker-title">选择次卡</text>
          <view v-for="cardId in pickerCardIds" :key="cardId" class="picker-item" @tap="confirmCard(cardId)">
            {{ getCardLabel(cardId) }}
          </view>
          <view class="picker-item cancel" @tap="closeCardPicker">取消</view>
        </view>
      </view>
    </block>
  </view>
</template>

<script setup>
import { computed, ref } from 'vue'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { membershipApi } from '@/modules/comprehensive/api/membership'
import { useComprehensiveSessionStore } from '@/modules/comprehensive/stores/session'
import { formatTimeRange } from '@/modules/comprehensive/utils/date'
import UnauthLoginPanel from '@/components/UnauthLoginPanel.vue'

const session = useComprehensiveSessionStore()
const preselectedCardId = ref('')
const sessions = ref([])
const cards = ref([])
const page = ref(1)
const pageSize = 20
const total = ref(0)
const isLoading = ref(false)
const isLoadingMore = ref(false)
const isSubmitting = ref(false)
const cardPickerVisible = ref(false)
const pendingSession = ref(null)

const hasMore = computed(() => sessions.value.length < total.value)

onLoad(async (query) => {
  preselectedCardId.value = query.card_id ? String(query.card_id) : ''
  await session.init()
  if (session.isLoggedIn) loadAll()
})

onPullDownRefresh(() => {
  loadAll().finally(() => uni.stopPullDownRefresh())
})

onReachBottom(() => {
  if (!hasMore.value || isLoadingMore.value) return
  page.value += 1
  loadSessions(false)
})

const loadAll = async () => {
  await Promise.all([
    loadSessions(true),
    loadCards()
  ])
}

const loadSessions = async (reset) => {
  if (reset) {
    page.value = 1
    isLoading.value = true
  } else {
    isLoadingMore.value = true
  }
  try {
    const data = await membershipApi.getAvailableSessions({ page: page.value, pageSize })
    let items = data.items
    if (preselectedCardId.value) {
      items = items.filter((item) => item.available_card_ids.includes(Number(preselectedCardId.value)))
    }
    sessions.value = reset ? items : [...sessions.value, ...items]
    if (preselectedCardId.value && data.items.length < data.page_size) {
      total.value = sessions.value.length
    } else {
      total.value = data.total
    }
  } finally {
    isLoading.value = false
    isLoadingMore.value = false
  }
}

const loadCards = async () => {
  const data = await membershipApi.getCards({ page: 1, pageSize: 50 })
  cards.value = data.items.filter((card) => card.status === 'available' && card.remaining_count > 0)
}

const onSessionTap = (session) => {
  if (isSubmitting.value) return
  if (session.remaining_count <= 0) {
    uni.showToast({ title: '该课程已约满', icon: 'none' })
    return
  }
  const availableIds = session.available_card_ids
  if (availableIds.length === 0) {
    uni.showToast({ title: '暂无可用次卡', icon: 'none' })
    return
  }
  if (preselectedCardId.value) {
    submitBooking(preselectedCardId.value, session.id)
    return
  }
  if (availableIds.length === 1) {
    submitBooking(String(availableIds[0]), session.id)
    return
  }
  pendingSession.value = session
  cardPickerVisible.value = true
}

const submitBooking = async (cardId, sessionId) => {
  if (isSubmitting.value) return
  isSubmitting.value = true
  uni.showLoading({ title: '提交中...' })
  try {
    const booking = await membershipApi.createCardBooking({ cardId, sessionId })
    uni.hideLoading()
    uni.redirectTo({ url: `/pages/comprehensive/membership/booking-detail?id=${booking.id}` })
  } catch (error) {
    uni.hideLoading()
  } finally {
    isSubmitting.value = false
    cardPickerVisible.value = false
    pendingSession.value = null
  }
}

const pickerCardIds = computed(() => {
  if (!pendingSession.value) return []
  return pendingSession.value.available_card_ids.map(String)
})

const getCardLabel = (cardId) => {
  const card = cards.value.find((item) => String(item.id) === String(cardId))
  if (!card) return `次卡 #${cardId}`
  return `${card.plan_name}（剩余${card.remaining_count}次）`
}

const confirmCard = (cardId) => {
  if (!pendingSession.value) return
  submitBooking(cardId, pendingSession.value.id)
}

const closeCardPicker = () => {
  cardPickerVisible.value = false
  pendingSession.value = null
}

const login = async () => {
  await session.login()
  loadAll()
}
</script>

<style lang="scss" scoped>
.available-page {
  min-height: 100vh;
  background: $bg-color-soft;
}

.session-list {
  display: flex;
  flex-direction: column;
  gap: $spacing-md;
  padding: $spacing-md;
}

.session-card {
  display: flex;
  gap: $spacing-md;
}

.session-cover {
  width: 180rpx;
  height: 172rpx;
  flex-shrink: 0;
  border-radius: $border-radius-base;
  background: $bg-color-hover;
}

.session-info {
  flex: 1;
  min-width: 0;
}

.session-top,
.session-bottom {
  display: flex;
  justify-content: space-between;
  gap: $spacing-sm;
}

.session-title {
  flex: 1;
  color: $text-color-main;
  font-size: 30rpx;
  font-weight: 900;
  line-height: 1.35;
}

.time-line {
  display: block;
  margin-top: $spacing-sm;
  color: $color-primary;
  font-size: 24rpx;
  font-weight: 800;
}

.meta {
  display: block;
  margin-top: 6rpx;
  color: $text-color-muted;
  font-size: 23rpx;
}

.session-price {
  color: $text-color-main;
  font-size: 28rpx;
  font-weight: 900;
}

.picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 100;
  display: flex;
  align-items: flex-end;
}

.picker-sheet {
  width: 100%;
  background: $bg-color-main;
  border-radius: $border-radius-lg $border-radius-lg 0 0;
  padding: $spacing-md;
  padding-bottom: calc($spacing-md + env(safe-area-inset-bottom));
}

.picker-title {
  display: block;
  text-align: center;
  color: $text-color-muted;
  font-size: 24rpx;
  margin-bottom: $spacing-sm;
}

.picker-item {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: $text-color-main;
  font-size: 28rpx;
  font-weight: 800;
  border-bottom: 1rpx solid $bg-color-hover;
}

.picker-item.cancel {
  color: $text-color-muted;
  font-weight: 600;
  border-bottom: none;
  margin-top: $spacing-sm;
}
</style>
