<template>
  <view class="page">
    <NavBar title="我的邀请" :showBack="true">
      <template #right>
        <view class="nav-action" @click="goToInvite">
          <view class="invite-icon"></view>
        </view>
      </template>
    </NavBar>

    <view class="content">
      <!-- 统计概览 -->
      <view class="stats-header" v-if="statistics">
        <view class="stat-card">
          <text class="stat-num">{{ statistics.totalInvite || 0 }}</text>
          <text class="stat-label">总邀请数</text>
        </view>
        <view class="stat-card success">
          <text class="stat-num">{{ statistics.validInvite || 0 }}</text>
          <text class="stat-label">已激活</text>
        </view>
        <view class="stat-card primary">
          <text class="stat-num">{{ statistics.rewardCount || 0 }}</text>
          <text class="stat-label">已获奖励</text>
        </view>
      </view>

      <!-- 双向奖励说明 -->
      <view class="dual-reward-notice">
        <view class="notice-icon">💡</view>
        <text class="notice-text">统计包含：邀请人推荐奖励 + 被邀请人新人优惠券</text>
      </view>

      <!-- 邀请记录列表 -->
      <view class="list-section">
        <view class="list-header">
          <text class="list-title">邀请记录</text>
          <text class="list-count">共 {{ total }} 条</text>
        </view>

        <scroll-view
          scroll-y
          class="records-list"
          @scrolltolower="loadMore"
          :refresher-enabled="true"
          :refresher-triggered="isRefreshing"
          @refresherrefresh="onRefresh"
        >
          <view class="record-list">
            <view
              class="record-item"
              v-for="(item, index) in recordList"
              :key="item.id"
            >
              <view class="record-left">
                <view class="avatar-placeholder">
                  <text class="avatar-text">{{ getAvatarText(item.inviteeName) }}</text>
                </view>
              </view>

              <view class="record-content">
                <view class="record-header">
                  <text class="invitee-name">{{ item.inviteeName || '用户' + (index + 1) }}</text>
                  <view class="status-tag" :class="getStatusClass(item.status)">
                    {{ getStatusText(item.status) }}
                  </view>
                </view>

                <view class="record-body">
                  <view class="info-row">
                    <view class="info-icon phone"></view>
                    <text class="info-text">{{ maskPhone(item.inviteePhone) }}</text>
                  </view>
                  <view class="info-row">
                    <view class="info-icon time"></view>
                    <text class="info-text">邀请时间：{{ formatTime(item.inviteTime) }}</text>
                  </view>
                  <view class="info-row" v-if="item.activateTime">
                    <view class="info-icon activate"></view>
                    <text class="info-text">激活时间：{{ formatTime(item.activateTime) }}</text>
                  </view>
                  <view class="info-row" v-if="item.rewardTime">
                    <view class="info-icon reward"></view>
                    <text class="info-text">奖励发放：{{ formatTime(item.rewardTime) }}</text>
                  </view>
                </view>

                <view class="record-reward" v-if="item.couponName && item.couponAmount">
                  <view class="reward-badge" :class="getRewardTypeClass(item.rewardType)">
                    <text class="reward-type-tag">{{ getRewardTypeText(item.rewardType) }}</text>
                    <text class="reward-amount">+¥{{ item.couponAmount }}</text>
                    <text class="reward-name">{{ item.couponName }}</text>
                  </view>
                </view>
              </view>
            </view>

            <!-- 空状态 -->
            <view class="empty-state" v-if="!isLoading && recordList.length === 0">
              <view class="empty-icon"></view>
              <text class="empty-text">暂无邀请记录</text>
              <text class="empty-tip">快去邀请好友吧！</text>
              <button class="empty-btn" @click="goToInvite">立即邀请</button>
            </view>

            <!-- 加载更多 -->
            <view class="loading-more" v-if="isLoadingMore">
              <view class="loading-spinner"></view>
              <text class="loading-text">加载中...</text>
            </view>

            <view class="no-more" v-if="!hasMore && recordList.length > 0">
              <text>没有更多了</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { logger } from '@/utils/logger';
import NavBar from '@/components/NavBar.vue';
import { getMyInviteRecords, getMyInviteStatistics, InviteStatus, InviteStatusLabel } from '@/api/invite';
import type { InviteRecord, InviteStatistics, InviteQueryParams } from '@/api/invite';

const statistics = ref<InviteStatistics | null>(null);
const recordList = ref<InviteRecord[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = 10;
const isLoading = ref(false);
const isLoadingMore = ref(false);
const isRefreshing = ref(false);
const hasMore = ref(true);

onMounted(() => {
  loadStatistics();
  loadData();
});

const loadStatistics = async () => {
  try {
    statistics.value = await getMyInviteStatistics();
  } catch (error) {
    logger.warn('加载统计数据失败', error);
  }
};

const loadData = async (reset = false) => {
  if (reset) {
    page.value = 1;
    hasMore.value = true;
  }

  if (isLoading.value) return;
  isLoading.value = true;

  try {
    const params: InviteQueryParams = {
      page: page.value,
      pageSize
    };

    const result = await getMyInviteRecords(params);

    if (reset) {
      recordList.value = result.list;
    } else {
      recordList.value = [...recordList.value, ...result.list];
    }

    total.value = result.total;
    hasMore.value = recordList.value.length < result.total;
  } catch (error) {
    logger.warn('加载邀请记录失败', error);
  } finally {
    isLoading.value = false;
    isRefreshing.value = false;
    isLoadingMore.value = false;
  }
};

const loadMore = () => {
  if (!hasMore.value || isLoadingMore.value) return;

  isLoadingMore.value = true;
  page.value++;
  loadData();
};

const onRefresh = () => {
  isRefreshing.value = true;
  loadData(true);
  loadStatistics();
};

const maskPhone = (phone: string) => {
  if (!phone || phone.length < 7) return phone;

  // 如果已经是脱敏格式，直接返回
  if (phone.includes('*')) return phone;

  return phone.substring(0, 3) + '****' + phone.substring(phone.length - 4);
};

const getStatusClass = (status: InviteStatus) => {
  const classMap: Record<InviteStatus, string> = {
    [InviteStatus.PENDING]: 'pending',
    [InviteStatus.ACTIVATED]: 'activated',
    [InviteStatus.REWARDED]: 'rewarded',
    [InviteStatus.FAILED]: 'failed'
  };
  return classMap[status] || '';
};

const getStatusText = (status: InviteStatus) => {
  const textMap: Record<InviteStatus, string> = {
    [InviteStatus.PENDING]: InviteStatusLabel.PENDING,
    [InviteStatus.ACTIVATED]: InviteStatusLabel.ACTIVATED,
    [InviteStatus.REWARDED]: InviteStatusLabel.REWARDED,
    [InviteStatus.FAILED]: InviteStatusLabel.FAILED
  };
  return textMap[status] || status;
};

const formatTime = (timeStr: string) => {
  if (!timeStr) return '';
  return timeStr.replace('T', ' ').substring(0, 19);
};

const getAvatarText = (name?: string) => {
  if (!name) return '?';
  return name.charAt(name.length - 1);
};

// 奖励类型判断（区分邀请人奖励和被邀请人新人券）
const getRewardTypeClass = (rewardType?: string) => {
  const typeMap: Record<string, string> = {
    'inviter': 'type-inviter',      // 邀请人推荐奖励
    'invitee': 'type-invitee'       // 被邀请人新人券
  };
  return typeMap[rewardType || ''] || '';
};

const getRewardTypeText = (rewardType?: string) => {
  const textMap: Record<string, string> = {
    'inviter': '推荐奖',
    'invitee': '新人券'
  };
  return textMap[rewardType || ''] || '';
};

const goToInvite = () => {
  uni.navigateTo({
    url: '/pages/invite/index'
  });
};
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: $bg-color-page;
  display: flex;
  flex-direction: column;
}

.nav-action {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.invite-icon {
  width: 36rpx;
  height: 36rpx;
  border: 3rpx solid $info-color;
  border-radius: 50%;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: -6rpx;
    right: -6rpx;
    width: 14rpx;
    height: 14rpx;
    background: $info-color;
    border-radius: 50%;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: -2rpx;
    right: -2rpx;
    width: 16rpx;
    height: 10rpx;
    border-left: 3rpx solid $info-color;
    border-bottom: 3rpx solid $info-color;
    transform: rotate(-45deg);
  }
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.stats-header {
  display: flex;
  padding: 24rpx;
  background: $bg-color-card;
  gap: 20rpx;
}

.dual-reward-notice {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 24rpx;
  background: $primary-color-bg;
  margin: 0 24rpx 16rpx;
  border-radius: 10rpx;
  border: 1rpx solid $primary-color-light;
}

.notice-icon {
  font-size: 28rpx;
  margin-right: 10rpx;
}

.notice-text {
  font-size: 24rpx;
  color: $primary-color-dark;
}

.stat-card {
  flex: 1;
  background: $bg-color-page;
  border-radius: 16rpx;
  padding: 24rpx 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1rpx solid $border-color;

  &.success {
    background: $success-color-bg;
    border-color: $success-color-bg;

    .stat-num {
      color: $primary-color-dark;
    }

    .stat-label {
      color: $success-color;
    }
  }

  &.primary {
    background: $info-color-bg;
    border-color: $info-color-bg;

    .stat-num {
      color: $info-color;
    }

    .stat-label {
      color: $info-color;
    }
  }
}

.stat-num {
  font-size: 40rpx;
  font-weight: 700;
  color: $text-color-primary;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 22rpx;
  color: $text-color-tertiary;
}

.list-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 24rpx;
  background: $bg-color-card;
  border-top: 1rpx solid $border-color;
}

.list-title {
  font-size: 28rpx;
  font-weight: 600;
  color: $text-color-primary;
}

.list-count {
  font-size: 24rpx;
  color: $text-color-muted;
}

.records-list {
  flex: 1;
  height: 0;
}

.record-list {
  padding: 0 24rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
}

.record-item {
  display: flex;
  align-items: flex-start;
  background: $bg-color-card;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  border: 1rpx solid $border-color;
}

.record-left {
  margin-right: 20rpx;
}

.avatar-placeholder {
  width: 80rpx;
  height: 80rpx;
  background: linear-gradient(135deg, $primary-color 0%, $primary-color-dark 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  font-size: 32rpx;
  font-weight: 600;
  color: $bg-color-card;
}

.record-content {
  flex: 1;
  min-width: 0;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.invitee-name {
  font-size: 28rpx;
  font-weight: 600;
  color: $text-color-primary;
}

.status-tag {
  padding: 4rpx 16rpx;
  border-radius: 8rpx;
  font-size: 22rpx;
  font-weight: 500;
  white-space: nowrap;
  margin-left: 12rpx;

  &.pending {
    background: $bg-color-secondary;
    color: $text-color-tertiary;
  }

  &.activated {
    background: $success-color-bg;
    color: $primary-color-dark;
  }

  &.rewarded {
    background: $info-color-bg;
    color: $info-color;
  }

  &.failed {
    background: $error-color-bg;
    color: $error-color;
  }
}

.record-body {
  margin-bottom: 12rpx;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.info-icon {
  width: 26rpx;
  height: 26rpx;
  margin-right: 8rpx;
  border-radius: 50%;

  &.phone {
    background: $info-color-bg;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 10rpx;
      height: 16rpx;
      border: 2rpx solid $info-color;
      border-radius: 3rpx;
    }

    &::after {
      content: '';
      position: absolute;
      bottom: 3rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 4rpx;
      height: 2rpx;
      background: $info-color;
      border-radius: 1rpx;
    }
  }

  &.time {
    background: $primary-color-bg;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 11rpx;
      height: 11rpx;
      border: 2rpx solid $primary-color;
      border-radius: 50%;
    }

    &::after {
      content: '';
      position: absolute;
      top: 7rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 2rpx;
      height: 5rpx;
      background: $primary-color;
    }
  }

  &.activate {
    background: $success-color-bg;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 12rpx;
      height: 8rpx;
      border: 2rpx solid $primary-color;
      border-radius: 2rpx;
    }

    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 4rpx;
      height: 4rpx;
      background: $primary-color;
      border-radius: 50%;
    }
  }

  &.reward {
    background: $warning-color-bg;
    position: relative;

    &::before {
      content: '¥';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 14rpx;
      font-weight: 700;
      color: $warning-color;
    }
  }
}

.info-text {
  font-size: 24rpx;
  color: $text-color-tertiary;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.record-reward {
  padding-top: 12rpx;
  border-top: 1rpx solid $bg-color-secondary;
}

.reward-badge {
  display: inline-flex;
  align-items: center;
  padding: 8rpx 16rpx;
  background: linear-gradient(135deg, $primary-color-bg 0%, $primary-color-light 100%);
  border-radius: 8rpx;
  gap: 8rpx;

  &.type-inviter {
    background: linear-gradient(135deg, $info-color-bg 0%, $info-color-bg 100%);

    .reward-amount {
      color: $info-color;
    }

    .reward-name {
      color: $text-color-primary;
    }
  }

  &.type-invitee {
    background: linear-gradient(135deg, $success-color-bg 0%, $success-color-bg 100%);

    .reward-amount {
      color: $primary-color-dark;
    }

    .reward-name {
      color: $success-color;
    }
  }
}

.reward-type-tag {
  font-size: 20rpx;
  font-weight: 600;
  padding: 2rpx 10rpx;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 6rpx;
  color: $primary-color-dark;
}

.reward-amount {
  font-size: 26rpx;
  font-weight: 700;
  color: $primary-color-dark;
}

.reward-name {
  font-size: 22rpx;
  color: $primary-color-dark;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 40rpx;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  background: $bg-color-secondary;
  border-radius: 50%;
  margin-bottom: 32rpx;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -60%);
    width: 56rpx;
    height: 36rpx;
    border: 4rpx solid $text-color-placeholder;
    border-radius: 8rpx 8rpx 0 0;
  }

  &::after {
    content: '';
    position: absolute;
    top: 58%;
    left: 50%;
    transform: translateX(-50%);
    width: 6rpx;
    height: 18rpx;
    background: $text-color-placeholder;
  }
}

.empty-text {
  font-size: 30rpx;
  color: $text-color-tertiary;
  margin-bottom: 12rpx;
}

.empty-tip {
  font-size: 26rpx;
  color: $text-color-muted;
  margin-bottom: 32rpx;
}

.empty-btn {
  padding: 20rpx 48rpx;
  background: linear-gradient(135deg, $primary-color 0%, $primary-color-dark 100%);
  border-radius: 44rpx;
  font-size: 28rpx;
  font-weight: 500;
  color: $bg-color-card;
  border: none;

  &:active {
    opacity: 0.9;
  }
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx;
}

.loading-spinner {
  width: 32rpx;
  height: 32rpx;
  border: 3rpx solid $border-color;
  border-top-color: $primary-color;
  border-radius: 50%;
  animation: rotate 0.8s linear infinite;

  @keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
}

.loading-text {
  font-size: 24rpx;
  color: $text-color-muted;
  margin-left: 12rpx;
}

.no-more {
  text-align: center;
  padding: 24rpx;

  text {
    font-size: 24rpx;
    color: $text-color-muted;
  }
}
</style>
