<template>
  <view class="page-room-detail">
    <!-- 顶部图片画廊 -->
    <view class="gallery-section">
      <swiper
        class="gallery-swiper"
        :indicator-dots="false"
        :autoplay="false"
        :circular="true"
        @change="handleSwiperChange"
      >
        <swiper-item v-for="(image, index) in roomImages" :key="index">
          <image
            :src="image"
            class="gallery-image"
            mode="aspectFill"
            @tap="previewImages(index)"
          />
        </swiper-item>
      </swiper>

      <!-- 顶部操作栏 -->
      <view class="top-bar">
        <view class="top-btn back-btn" @tap="handleBack">
          <u-icon name="arrow-left" :size="22" color="#1A1A1A" />
        </view>
        <view class="top-btn share-btn" @tap="handleShare">
          <u-icon name="share" :size="20" color="#1A1A1A" />
        </view>
      </view>

      <!-- 图片指示器 -->
      <view class="image-indicator">
        <text class="indicator-text">{{ currentImageIndex + 1 }} / {{ roomImages.length }}</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-wrapper">
      <!-- 房间标题卡片 -->
      <view class="title-card">
        <view class="title-row">
          <text class="room-title">{{ roomData.name }}</text>
          <view class="price-badge">
            <text class="price-amount">¥{{ calculatedPrice > 0 ? calculatedPrice.toFixed(2) : roomData.price }}</text>
            <text class="price-label">/晚</text>
          </view>
        </view>

        <view class="meta-row">
          <view class="meta-tag primary">
            <text class="tag-text">{{ roomTypeLabel }}</text>
          </view>
          <view class="meta-tag">
            <text class="tag-text">{{ roomData.area }}㎡</text>
          </view>
          <view class="meta-tag">
            <text class="tag-text">{{ roomData.bedType }}</text>
          </view>
          <view class="meta-tag">
            <text class="tag-text">{{ roomData.maxGuests }}人</text>
          </view>
        </view>

        <view v-if="availabilityText" class="availability-banner" :class="availabilityClass">
          <u-icon name="info-circle-fill" :size="16" :color="availabilityIconColor" />
          <text class="availability-text">{{ availabilityText }}</text>
        </view>
      </view>

      <!-- 房间亮点 -->
      <view v-if="roomHighlights.length > 0" class="highlights-card">
        <text class="card-title">房间亮点</text>
        <view class="highlights-grid">
          <view
            v-for="(highlight, index) in roomHighlights"
            :key="index"
            class="highlight-item"
          >
            <text class="highlight-text">{{ highlight.text }}</text>
          </view>
        </view>
      </view>

      <!-- 设施服务 -->
      <view class="facilities-card">
        <text class="card-title">设施与服务</text>
        <view class="facilities-list">
          <view
            v-for="(facility, index) in displayFacilities"
            :key="index"
            class="facility-chip"
          >
            <text class="facility-text">{{ facility }}</text>
          </view>
        </view>
        <view
          v-if="roomData.facilities && roomData.facilities.length > 6"
          class="view-more-btn"
          @tap="toggleFacilities"
        >
          <text class="view-more-text">
            {{ showAllFacilities ? '收起' : `查看全部 ${roomData.facilities.length} 项设施` }}
          </text>
          <u-icon
            :name="showAllFacilities ? 'arrow-up' : 'arrow-down'"
            :size="16"
            color="#666"
          />
        </view>
      </view>

      <!-- 房间描述 -->
      <view v-if="roomData.description" class="description-card">
        <text class="card-title">房间详情</text>
        <text class="description-content" :class="{ expanded: isDescExpanded }">
          {{ roomData.description }}
        </text>
        <view
          v-if="roomData.description.length > 80"
          class="read-more-btn"
          @tap="toggleDescription"
        >
          <text class="read-more-text">{{ isDescExpanded ? '收起' : '阅读更多' }}</text>
        </view>
      </view>

      <!-- 入住政策 -->
      <view class="policy-card">
        <text class="card-title">入住政策</text>
        <view class="policy-list">
          <view class="policy-item">
            <view class="policy-icon-box checkin">
              <u-icon name="clock-fill" :size="20" color="#4CAF50" />
            </view>
            <view class="policy-content">
              <text class="policy-label">入住时间</text>
              <text class="policy-value">14:00 后可办理入住</text>
            </view>
          </view>

          <view class="policy-item">
            <view class="policy-icon-box checkout">
              <u-icon name="clock-fill" :size="20" color="#FF9800" />
            </view>
            <view class="policy-content">
              <text class="policy-label">退房时间</text>
              <text class="policy-value">12:00 前需完成退房</text>
            </view>
          </view>

          <view class="policy-item">
            <view class="policy-icon-box cancel">
              <u-icon name="close-circle-fill" :size="20" color="#2196F3" />
            </view>
            <view class="policy-content">
              <text class="policy-label">取消政策</text>
              <text class="policy-value">入住前 24 小时可免费取消</text>
            </view>
          </view>

          <view class="policy-item">
            <view class="policy-icon-box notice">
              <u-icon name="warning-fill" :size="20" color="#F44336" />
            </view>
            <view class="policy-content">
              <text class="policy-label">入住须知</text>
              <text class="policy-value">需携带有效身份证件办理入住</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部占位 -->
      <view class="bottom-placeholder" />
    </view>

    <!-- 底部预订栏 -->
    <view class="booking-bar">
      <view class="booking-left">
        <view class="booking-price">
          <text class="booking-amount">¥{{ calculatedPrice > 0 ? calculatedPrice.toFixed(2) : roomData.price }}</text>
          <text class="booking-unit">/晚</text>
        </view>
        <text v-if="stockText" class="booking-stock">{{ stockText }}</text>
      </view>

      <view class="booking-actions">
        <view class="action-btn secondary" @tap="handleContact">
          <u-icon name="phone-fill" :size="20" color="#666" />
        </view>
        <view
          class="action-btn primary"
          :class="{ disabled: !isAvailable }"
          @tap="handleBook"
        >
          <text class="action-text">{{ isAvailable ? '立即预订' : '暂不可订' }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getRoomDetail, getRoomCalendar } from '@/api/user/room';
import type { Room } from '@/types/room';

// 常量
const DEFAULT_IMAGE = '/static/default-room.png';

// 房型标签映射
const ROOM_TYPE_LABELS: Record<string, string> = {
  hotel: '酒店客房',
  homestay: '民宿',
  apartment: '公寓',
  hostel: '青旅床位',
};

// 房间数据
const roomId = ref(0);
const roomData = ref<Partial<Room>>({});
const todayStock = ref(0);
const currentImageIndex = ref(0);
const checkInDate = ref('');
const checkOutDate = ref('');
const calculatedPrice = ref(0);

// UI状态
const showAllFacilities = ref(false);
const isDescExpanded = ref(false);

// 计算属性
const roomImages = computed(() => {
  const images = roomData.value.images || [];
  return images.length > 0 ? images : [roomData.value.coverImage || DEFAULT_IMAGE];
});

const roomTypeLabel = computed(() => {
  return ROOM_TYPE_LABELS[roomData.value.type || ''] || '房间';
});

const displayFacilities = computed(() => {
  const facilities = roomData.value.facilities || [];
  return showAllFacilities.value ? facilities : facilities.slice(0, 6);
});

const isAvailable = computed(() => {
  return todayStock.value > 0 && roomData.value.status === 'available';
});

const availabilityText = computed(() => {
  if (!isAvailable.value) return '当前不可预订';
  if (todayStock.value <= 3) return `仅剩 ${todayStock.value} 间`;
  return '房源充足';
});

const availabilityClass = computed(() => {
  if (!isAvailable.value) return 'unavailable';
  if (todayStock.value <= 3) return 'limited';
  return 'available';
});

const availabilityIconColor = computed(() => {
  if (!isAvailable.value) return '#F44336';
  if (todayStock.value <= 3) return '#FF9800';
  return '#4CAF50';
});

const stockText = computed(() => {
  if (!isAvailable.value) return '';
  if (todayStock.value <= 3) return `仅剩${todayStock.value}间`;
  return '';
});

const roomHighlights = computed(() => {
  const highlights = [];

  if (roomData.value.area && roomData.value.area >= 30) {
    highlights.push({ icon: 'fullscreen', text: '宽敞空间' });
  }

  if (roomData.value.facilities?.includes('WiFi')) {
    highlights.push({ icon: 'wifi', text: '高速WiFi' });
  }

  if (roomData.value.facilities?.includes('独立卫浴')) {
    highlights.push({ icon: 'droplet', text: '独立卫浴' });
  }

  if (roomData.value.facilities?.includes('阳台')) {
    highlights.push({ icon: 'flower', text: '观景阳台' });
  }

  return highlights;
});

// 初始化
function initializeFromUrl() {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  const options = currentPage.options || currentPage.$page?.options || {};
  roomId.value = Number(options.id) || 0;

  // 如果没有传入日期，使用当天日期
  if (options.checkIn) {
    checkInDate.value = options.checkIn;
  } else {
    const today = new Date();
    checkInDate.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
  }

  checkOutDate.value = options.checkOut || '';
}

// 获取房间详情
async function fetchRoomDetail() {
  if (!roomId.value) return;

  try {
    const response = await getRoomDetail(roomId.value);
    roomData.value = response.data || {};

    // 如果有入住日期，计算日历价格
    if (checkInDate.value) {
      await calculatePriceFromCalendar();
    }
  } catch (error) {
    console.error('获取房间详情失败:', error);
    uni.showToast({ title: '加载失败，请重试', icon: 'none' });
  }
}

// 根据日历计算价格
async function calculatePriceFromCalendar() {
  if (!roomId.value || !checkInDate.value) return;

  try {
    // 如果没有退房日期，使用入住日期的第二天
    const checkOut = checkOutDate.value || (() => {
      const date = new Date(checkInDate.value);
      date.setDate(date.getDate() + 1);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    })();

    const response = await getRoomCalendar(roomId.value, checkInDate.value, checkOut);
    const calendarData = response.data || [];

    if (calendarData.length > 0) {
      // 使用入住日期当天的价格
      calculatedPrice.value = Number(calendarData[0].price || 0);
    }
  } catch (error) {
    console.error('计算价格失败:', error);
  }
}

// 获取今日库存
async function fetchTodayStock() {
  if (!roomId.value) return;

  try {
    const today = new Date();
    const dateStr = today.toISOString().split('T')[0];
    const response = await getRoomCalendar(roomId.value, dateStr, dateStr);

    if (response.data && response.data.length > 0) {
      todayStock.value = response.data[0].stock || 0;
    }
  } catch (error) {
    console.error('获取库存失败:', error);
    todayStock.value = 0;
  }
}

// UI交互
function handleSwiperChange(e: any) {
  currentImageIndex.value = e.detail.current;
}

function toggleFacilities() {
  showAllFacilities.value = !showAllFacilities.value;
}

function toggleDescription() {
  isDescExpanded.value = !isDescExpanded.value;
}

function handleBack() {
  uni.navigateBack();
}

function handleShare() {
  uni.showToast({ title: '分享功能开发中', icon: 'none' });
}

function previewImages(current: number) {
  uni.previewImage({
    urls: roomImages.value,
    current: current,
  });
}

function handleContact() {
  uni.showModal({
    title: '联系房东',
    content: '是否拨打电话联系房东？',
    confirmText: '拨打',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({ title: '功能开发中', icon: 'none' });
      }
    },
  });
}

function handleBook() {
  if (!isAvailable.value) {
    uni.showToast({ title: '该房间暂不可预订', icon: 'none' });
    return;
  }

  uni.navigateTo({
    url: `/pages/order-create/index?roomId=${roomId.value}`,
  });
}

// 生命周期
onMounted(() => {
  initializeFromUrl();

  if (roomId.value) {
    fetchRoomDetail();
    fetchTodayStock();
  } else {
    uni.showToast({ title: '房间信息不存在', icon: 'none' });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style lang="scss" scoped>
@import '@/static/styles/design-tokens.scss';

.page-room-detail {
  min-height: 100vh;
  background: #FAFAFA;
}

/* ========== 图片画廊 ========== */
.gallery-section {
  position: relative;
  width: 100%;
  height: 600rpx;
  background: #000;
}

.gallery-swiper {
  width: 100%;
  height: 100%;
}

.gallery-image {
  width: 100%;
  height: 100%;
}

.top-bar {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  display: flex;
  justify-content: space-between;
  padding: 48rpx 24rpx 24rpx;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.3) 0%, transparent 100%);
}

.top-btn {
  width: 72rpx;
  height: 72rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20rpx);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.9);
    background: rgba(255, 255, 255, 1);
  }
}

.image-indicator {
  position: absolute;
  bottom: 32rpx;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  padding: 12rpx 24rpx;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10rpx);
  border-radius: 30rpx;
}

.indicator-text {
  font-size: 24rpx;
  color: #FFFFFF;
  font-weight: 500;
}

/* ========== 内容区域 ========== */
.content-wrapper {
  position: relative;
  margin-top: -40rpx;
  border-radius: 32rpx 32rpx 0 0;
  background: #FAFAFA;
  padding: 32rpx 20rpx 0;
}

/* ========== 标题卡片 ========== */
.title-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.04);
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.room-title {
  flex: 1;
  font-size: 38rpx;
  font-weight: 700;
  color: #1A1A1A;
  line-height: 1.4;
}

.price-badge {
  flex-shrink: 0;
  display: flex;
  align-items: baseline;
  gap: 4rpx;
  padding: 12rpx 20rpx;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.price-amount {
  font-size: 32rpx;
  font-weight: 700;
  color: #FFFFFF;
  line-height: 1;
}

.price-label {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.9);
}

.meta-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.meta-tag {
  padding: 10rpx 20rpx;
  background: #F5F5F5;
  border-radius: 12rpx;
  border: 1rpx solid #E8E8E8;

  &.primary {
    background: linear-gradient(135deg, #FFF5E6 0%, #FFE8CC 100%);
    border-color: #FFD699;

    .tag-text {
      color: #FF8C00;
      font-weight: 600;
    }
  }
}

.tag-text {
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
}

.availability-banner {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 16rpx 20rpx;
  border-radius: 12rpx;
  border: 1rpx solid;

  &.available {
    background: #E8F5E9;
    border-color: #81C784;
  }

  &.limited {
    background: #FFF3E0;
    border-color: #FFB74D;
  }

  &.unavailable {
    background: #FFEBEE;
    border-color: #E57373;
  }
}

.availability-text {
  font-size: 24rpx;
  font-weight: 600;
  color: #333;
}

/* ========== 亮点卡片 ========== */
.highlights-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.04);
}

.card-title {
  font-size: 30rpx;
  font-weight: 700;
  color: #1A1A1A;
  margin-bottom: 24rpx;
  display: block;
}

.highlights-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.highlight-item {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 20rpx;
  background: linear-gradient(135deg, #F8F9FA 0%, #FFFFFF 100%);
  border-radius: 16rpx;
  border: 1rpx solid #E8E8E8;
}

.highlight-icon-wrapper {
  width: 64rpx;
  height: 64rpx;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.highlight-icon {
  font-size: 32rpx;
}

.highlight-text {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
}

/* ========== 设施卡片 ========== */
.facilities-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.04);
}

.facilities-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 16rpx;
}

.facility-chip {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  background: #F8F9FA;
  border-radius: 30rpx;
  border: 1rpx solid #E8E8E8;
}

.facility-icon {
  font-size: 28rpx;
}

.facility-text {
  font-size: 24rpx;
  color: #333;
  font-weight: 500;
}

.view-more-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx;
  background: #F8F9FA;
  border-radius: 12rpx;
  transition: all 0.3s ease;

  &:active {
    background: #F0F0F0;
    transform: scale(0.98);
  }
}

.view-more-text {
  font-size: 26rpx;
  color: #666;
  font-weight: 500;
}

/* ========== 描述卡片 ========== */
.description-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.04);
}

.description-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.8;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;

  &.expanded {
    display: block;
    -webkit-line-clamp: unset;
  }
}

.read-more-btn {
  margin-top: 16rpx;
  text-align: center;
  padding: 12rpx;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
  }
}

.read-more-text {
  font-size: 26rpx;
  color: #667EEA;
  font-weight: 600;
}

/* ========== 政策卡片 ========== */
.policy-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.04);
}

.policy-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.policy-item {
  display: flex;
  gap: 20rpx;
  padding: 24rpx;
  background: #F8F9FA;
  border-radius: 16rpx;
}

.policy-icon-box {
  width: 72rpx;
  height: 72rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  &.checkin {
    background: rgba(76, 175, 80, 0.1);
  }

  &.checkout {
    background: rgba(255, 152, 0, 0.1);
  }

  &.cancel {
    background: rgba(33, 150, 243, 0.1);
  }

  &.notice {
    background: rgba(244, 67, 54, 0.1);
  }
}

.policy-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  justify-content: center;
}

.policy-label {
  font-size: 26rpx;
  color: #999;
}

.policy-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
  line-height: 1.5;
}

/* ========== 底部占位 ========== */
.bottom-placeholder {
  height: 140rpx;
}

/* ========== 底部预订栏 ========== */
.booking-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 24rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20rpx);
  border-top: 1rpx solid #E8E8E8;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.booking-left {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.booking-price {
  display: flex;
  align-items: baseline;
  gap: 4rpx;
}

.booking-amount {
  font-size: 44rpx;
  font-weight: 700;
  color: #667EEA;
  line-height: 1;
}

.booking-unit {
  font-size: 24rpx;
  color: #999;
}

.booking-stock {
  font-size: 22rpx;
  color: #FF9800;
  font-weight: 600;
}

.booking-actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  border-radius: 44rpx;
  transition: all 0.3s ease;

  &.secondary {
    width: 88rpx;
    background: #F5F5F5;
    border: 1rpx solid #E8E8E8;

    &:active {
      background: #EBEBEB;
      transform: scale(0.95);
    }
  }

  &.primary {
    padding: 0 56rpx;
    background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);

    &:active {
      transform: scale(0.95);
      box-shadow: 0 2rpx 12rpx rgba(102, 126, 234, 0.5);
    }

    &.disabled {
      background: #E0E0E0;
      box-shadow: none;
    }
  }
}

.action-text {
  font-size: 28rpx;
  color: #FFFFFF;
  font-weight: 700;
}
</style>
