<template>
  <div class="duo-practice-room">
    <!-- 顶部信息栏 -->
    <div class="room-header">
      <div class="header-left">
        <el-button text @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <div class="room-title">
          <h2>{{ store.roomInfo?.room_name || '双人对练' }}</h2>
          <div class="room-code-display">
            房间码：<span class="code">{{ store.roomCode }}</span>
            <el-button text size="small" @click="store.copyRoomCode">
              <el-icon><CopyDocument /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      <div class="header-right">
        <!-- 语音通话状态 -->
        <div class="voice-status" v-if="voiceCall.isCallActive.value">
          <el-icon class="voice-icon" :class="{ active: voiceCall.callState.value === 'connected' }">
            <Microphone />
          </el-icon>
          <span class="call-duration" v-if="voiceCall.callState.value === 'connected'">
            {{ voiceCall.formatDuration(voiceCall.callDuration.value) }}
          </span>
          <span class="call-status" v-else>{{ voiceCallStatusText }}</span>
        </div>
        <el-tag :type="statusType" size="large">{{ statusText }}</el-tag>
      </div>
    </div>

    <!-- 主体区域 -->
    <div class="room-body">
      <!-- 左侧：参与者和操作 -->
      <div class="participants-panel">
        <h3>参与者</h3>
        
        <!-- 房主 -->
        <div class="participant-card host">
          <div class="avatar">
            <el-avatar :size="48" :src="store.hostUser?.avatar_url">
              {{ store.hostUser?.full_name?.[0] || 'H' }}
            </el-avatar>
            <el-tag class="role-tag" size="small" type="warning">房主</el-tag>
          </div>
          <div class="info">
            <div class="name">{{ store.hostUser?.full_name || '等待中...' }}</div>
            <div class="role">扮演：{{ hostRoleName }}</div>
          </div>
          <div class="badge" v-if="store.isHost">
            <el-tag type="primary" size="small">我</el-tag>
          </div>
        </div>

        <!-- 嘉宾 -->
        <div class="participant-card guest" :class="{ empty: !store.guestUser }">
          <template v-if="store.guestUser">
            <div class="avatar">
              <el-avatar :size="48" :src="store.guestUser?.avatar_url">
                {{ store.guestUser?.full_name?.[0] || 'G' }}
              </el-avatar>
            </div>
            <div class="info">
              <div class="name">{{ store.guestUser?.full_name }}</div>
              <div class="role">扮演：{{ guestRoleName }}</div>
            </div>
            <div class="badge" v-if="!store.isHost">
              <el-tag type="primary" size="small">我</el-tag>
            </div>
          </template>
          <template v-else>
            <div class="empty-placeholder">
              <el-icon :size="32"><Plus /></el-icon>
              <span>等待对方加入</span>
            </div>
          </template>
        </div>

        <!-- 分享区域 -->
        <div class="share-section" v-if="store.isWaiting">
          <h4>邀请伙伴加入</h4>
          <div class="share-code">
            <span class="big-code">{{ store.roomCode }}</span>
          </div>
          <el-button type="primary" @click="store.copyShareLink" block>
            <el-icon><Share /></el-icon>
            复制邀请链接
          </el-button>
        </div>

        <!-- 语音通话控制 -->
        <div class="voice-control" v-if="store.isPracticing">
          <h4>语音通话</h4>
          
          <!-- 未通话状态 -->
          <div class="voice-idle" v-if="voiceCall.callState.value === 'idle'">
            <el-button 
              type="success" 
              size="large" 
              round
              @click="voiceCall.startCall"
            >
              <el-icon><Microphone /></el-icon>
              发起语音
            </el-button>
            <p class="voice-hint">点击发起语音通话，实时对话</p>
          </div>

          <!-- 呼叫中状态 -->
          <div class="voice-ringing" v-else-if="voiceCall.callState.value === 'ringing'">
            <div class="ringing-animation">
              <el-icon :size="48" class="pulse"><Microphone /></el-icon>
            </div>
            <p>正在呼叫对方...</p>
            <el-button type="danger" round @click="voiceCall.endCall">取消</el-button>
          </div>

          <!-- 来电状态 -->
          <div class="voice-incoming" v-else-if="voiceCall.callState.value === 'ringing' && !isCallInitiator">
            <div class="incoming-animation">
              <el-icon :size="48" class="shake"><PhoneFilled /></el-icon>
            </div>
            <p>对方发起语音通话</p>
            <div class="incoming-actions">
              <el-button type="success" circle size="large" @click="voiceCall.answerCall">
                <el-icon><Microphone /></el-icon>
              </el-button>
              <el-button type="danger" circle size="large" @click="voiceCall.rejectCall">
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>

          <!-- 连接中状态 -->
          <div class="voice-connecting" v-else-if="voiceCall.callState.value === 'connecting'">
            <el-icon :size="32" class="spin"><Loading /></el-icon>
            <p>正在连接...</p>
          </div>

          <!-- 通话中状态 -->
          <div class="voice-connected" v-else-if="voiceCall.callState.value === 'connected'">
            <div class="call-info">
              <div class="call-timer">{{ voiceCall.formatDuration(voiceCall.callDuration.value) }}</div>
              <div class="audio-levels">
                <div class="level-item">
                  <span>我</span>
                  <div class="level-bar">
                    <div class="level-fill" :style="{ width: (voiceCall.localAudioLevel.value * 100) + '%' }"></div>
                  </div>
                </div>
                <div class="level-item">
                  <span>对方</span>
                  <div class="level-bar">
                    <div class="level-fill remote" :style="{ width: (voiceCall.remoteAudioLevel.value * 100) + '%' }"></div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 实时转写 -->
            <div class="transcription" v-if="voiceCall.currentTranscript.value">
              <el-icon><Edit /></el-icon>
              <span>{{ voiceCall.currentTranscript.value }}</span>
            </div>

            <div class="call-controls">
              <el-button 
                :type="voiceCall.isMuted.value ? 'danger' : 'default'" 
                circle 
                size="large"
                @click="voiceCall.toggleMute"
              >
                <el-icon>
                  <MuteNotification v-if="voiceCall.isMuted.value" />
                  <Microphone v-else />
                </el-icon>
              </el-button>
              <el-button type="danger" circle size="large" @click="voiceCall.endCall">
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <template v-if="store.isHost && store.isReady">
            <el-button type="primary" size="large" @click="store.startPractice" :loading="store.isLoading">
              开始对练
            </el-button>
          </template>
          <template v-if="store.isPracticing">
            <el-button type="danger" size="large" @click="handleEndPractice">
              结束对练
            </el-button>
          </template>
          <template v-if="store.isCompleted">
            <el-button type="primary" size="large" @click="viewReport">
              查看报告
            </el-button>
          </template>
          <el-button @click="handleLeave" v-if="!store.isPracticing">
            离开房间
          </el-button>
        </div>
      </div>

      <!-- 右侧：对话区域 -->
      <div class="chat-panel">
        <div class="chat-header">
          <span>对话记录</span>
          <span class="turn-count" v-if="store.roomInfo">
            {{ store.roomInfo.total_turns }} 轮对话
          </span>
        </div>
        
        <div class="chat-messages" ref="messagesContainer">
          <!-- 系统消息 -->
          <div 
            v-for="msg in store.messages" 
            :key="msg.id" 
            class="message"
            :class="getMessageClass(msg)"
          >
            <template v-if="msg.message_type === 'chat'">
              <div class="message-avatar">
                <el-avatar :size="36">
                  {{ msg.role_name?.[0] || '?' }}
                </el-avatar>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <span class="sender-name">{{ msg.role_name }}</span>
                  <span class="message-time">{{ formatMessageTime(msg.created_at) }}</span>
                </div>
                <div class="message-body">{{ msg.content }}</div>
              </div>
            </template>
            <template v-else>
              <div class="system-message">
                {{ msg.content }}
              </div>
            </template>
          </div>
          
          <!-- 空状态 -->
          <div v-if="store.messages.length === 0" class="empty-chat">
            <el-empty description="对练开始后，对话将显示在这里" />
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input" v-if="store.isPracticing">
          <el-input
            v-model="store.inputMessage"
            type="textarea"
            :rows="2"
            placeholder="输入消息..."
            @keydown.enter.ctrl="store.sendMessage()"
          />
          <el-button type="primary" @click="store.sendMessage()" :disabled="!store.inputMessage.trim()">
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, CopyDocument, Plus, Share, Microphone, 
  Close, Loading, MuteNotification, Edit, PhoneFilled 
} from '@element-plus/icons-vue'
import { useDuoPracticeStore } from '@/stores/duoPracticeStore'
import { useVoiceCall } from '@/composables/useVoiceCall'
import type { RoomMessage } from '@/api/duoPractice'

const route = useRoute()
const router = useRouter()
const store = useDuoPracticeStore()
const messagesContainer = ref<HTMLElement | null>(null)
const isCallInitiator = ref(false)

// 语音通话
const voiceCall = useVoiceCall({
  roomCode: computed(() => store.roomCode).value,
  onTranscript: handleTranscript
})

// 语音通话状态文本
const voiceCallStatusText = computed(() => {
  const statusMap: Record<string, string> = {
    'idle': '未连接',
    'requesting': '请求中...',
    'ringing': '呼叫中...',
    'connecting': '连接中...',
    'connected': '通话中',
    'ended': '已结束'
  }
  return statusMap[voiceCall.callState.value] || ''
})

// 处理语音转写
function handleTranscript(text: string, isFinal: boolean) {
  if (isFinal && text.trim()) {
    // 将转写的文字作为消息发送
    store.sendMessage(text)
  }
}

// 计算属性
const statusType = computed(() => {
  const map: Record<string, string> = {
    'waiting': 'warning',
    'ready': 'info',
    'practicing': 'success',
    'completed': '',
    'canceled': 'danger'
  }
  return map[store.roomStatus] || ''
})

const statusText = computed(() => {
  const map: Record<string, string> = {
    'waiting': '等待加入',
    'ready': '准备就绪',
    'practicing': '对练中',
    'completed': '已完成',
    'canceled': '已取消'
  }
  return map[store.roomStatus] || store.roomStatus
})

const hostRoleName = computed(() => {
  if (!store.roomInfo) return ''
  return store.roomInfo.host_role === 'A' 
    ? store.roomInfo.role_a_name 
    : store.roomInfo.role_b_name
})

const guestRoleName = computed(() => {
  if (!store.roomInfo) return ''
  return store.roomInfo.host_role === 'A' 
    ? store.roomInfo.role_b_name 
    : store.roomInfo.role_a_name
})

// 方法
const handleBack = () => {
  router.push('/trainee/duo-practice')
}

const handleLeave = async () => {
  try {
    await ElMessageBox.confirm('确定要离开房间吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await store.leaveRoom()
    router.push('/trainee/duo-practice')
  } catch {
    // 用户取消
  }
}

const handleEndPractice = async () => {
  try {
    await ElMessageBox.confirm('确定要结束对练吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await store.endPractice()
  } catch {
    // 用户取消
  }
}

const viewReport = () => {
  router.push(`/trainee/duo-practice/report/${store.roomInfo?.id}`)
}

const getMessageClass = (msg: RoomMessage) => {
  if (msg.message_type !== 'chat') return 'system'
  const isMe = msg.user_id && (
    (store.isHost && msg.user_id === store.hostUser?.id) ||
    (!store.isHost && msg.user_id === store.guestUser?.id)
  )
  return isMe ? 'mine' : 'other'
}

const formatMessageTime = (time: string) => {
  const date = new Date(time)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 监听消息变化，处理信令消息并自动滚动
watch(() => store.messages, (messages) => {
  // 处理新消息
  const latestMsg = messages[messages.length - 1]
  if (latestMsg) {
    // 检查是否是信令消息
    const signalTypes = ['voice_start', 'voice_offer', 'voice_answer', 'ice_candidate', 'voice_end']
    if (signalTypes.includes(latestMsg.message_type)) {
      // 不处理自己发的信令
      const myUserId = store.isHost ? store.hostUser?.id : store.guestUser?.id
      if (latestMsg.user_id !== myUserId) {
        try {
          const payload = latestMsg.content ? JSON.parse(latestMsg.content) : {}
          voiceCall.handleSignal(latestMsg.message_type, payload, latestMsg.user_id || 0)
        } catch (e) {
          console.error('[DuoPracticeRoom] 解析信令失败:', e)
        }
      }
    }
  }
  scrollToBottom()
}, { deep: true })

// 初始化
onMounted(async () => {
  const roomCode = route.params.code as string
  if (roomCode) {
    store.roomCode = roomCode
    await store.fetchRoomDetail()
    
    // 开始轮询消息
    store.startPolling()
  }
})

onUnmounted(() => {
  store.stopPolling()
  // 结束语音通话
  if (voiceCall.isCallActive.value) {
    voiceCall.endCall()
  }
})
</script>

<style scoped lang="scss">
.duo-practice-room {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #fff;
  border-bottom: 1px solid #eee;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .room-title {
      h2 {
        font-size: 18px;
        font-weight: 600;
        margin: 0 0 4px 0;
      }
      
      .room-code-display {
        font-size: 13px;
        color: #666;
        
        .code {
          font-family: monospace;
          color: #667eea;
          font-weight: 500;
          letter-spacing: 2px;
        }
      }
    }
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .voice-status {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 6px 12px;
      background: #f0f9eb;
      border-radius: 20px;
      
      .voice-icon {
        color: #67c23a;
        
        &.active {
          animation: pulse 1.5s infinite;
        }
      }
      
      .call-duration {
        font-family: monospace;
        font-size: 14px;
        font-weight: 500;
        color: #67c23a;
      }
      
      .call-status {
        font-size: 13px;
        color: #67c23a;
      }
    }
  }
}

.room-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.participants-panel {
  width: 320px;
  background: #fff;
  border-right: 1px solid #eee;
  padding: 24px;
  display: flex;
  flex-direction: column;
  
  h3 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
  }
  
  .participant-card {
    display: flex;
    align-items: center;
    padding: 16px;
    border-radius: 12px;
    background: #f8f9fc;
    margin-bottom: 12px;
    
    .avatar {
      position: relative;
      margin-right: 12px;
      
      .role-tag {
        position: absolute;
        bottom: -4px;
        right: -4px;
        transform: scale(0.8);
      }
    }
    
    .info {
      flex: 1;
      
      .name {
        font-weight: 500;
        font-size: 15px;
      }
      
      .role {
        font-size: 13px;
        color: #666;
        margin-top: 2px;
      }
    }
    
    &.empty {
      border: 2px dashed #ddd;
      background: transparent;
      justify-content: center;
      min-height: 80px;
      
      .empty-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        color: #999;
        
        span {
          margin-top: 8px;
          font-size: 13px;
        }
      }
    }
  }
  
  .share-section {
    margin-top: 24px;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    color: #fff;
    
    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
    }
    
    .share-code {
      text-align: center;
      margin-bottom: 16px;
      
      .big-code {
        font-size: 32px;
        font-family: monospace;
        font-weight: 700;
        letter-spacing: 6px;
      }
    }
  }
  
  .voice-control {
    margin-top: 24px;
    padding: 20px;
    background: #f8f9fc;
    border-radius: 12px;
    
    h4 {
      margin: 0 0 16px 0;
      font-size: 14px;
      font-weight: 600;
      color: #333;
    }
    
    .voice-idle {
      text-align: center;
      
      .voice-hint {
        margin-top: 12px;
        font-size: 12px;
        color: #999;
      }
    }
    
    .voice-ringing, .voice-incoming, .voice-connecting {
      text-align: center;
      
      p {
        margin: 12px 0;
        color: #666;
      }
      
      .ringing-animation, .incoming-animation {
        .el-icon {
          color: #67c23a;
        }
        
        .pulse {
          animation: pulse 1.5s infinite;
        }
        
        .shake {
          animation: shake 0.5s infinite;
        }
      }
      
      .incoming-actions {
        display: flex;
        justify-content: center;
        gap: 24px;
        margin-top: 16px;
      }
    }
    
    .voice-connecting {
      .spin {
        animation: spin 1s linear infinite;
        color: #409eff;
      }
    }
    
    .voice-connected {
      .call-info {
        .call-timer {
          text-align: center;
          font-size: 24px;
          font-weight: 600;
          font-family: monospace;
          color: #67c23a;
          margin-bottom: 16px;
        }
        
        .audio-levels {
          .level-item {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
            
            span {
              width: 40px;
              font-size: 12px;
              color: #666;
            }
            
            .level-bar {
              flex: 1;
              height: 6px;
              background: #e0e0e0;
              border-radius: 3px;
              overflow: hidden;
              
              .level-fill {
                height: 100%;
                background: linear-gradient(90deg, #67c23a, #95d475);
                transition: width 0.1s ease;
                
                &.remote {
                  background: linear-gradient(90deg, #409eff, #79bbff);
                }
              }
            }
          }
        }
      }
      
      .transcription {
        display: flex;
        align-items: flex-start;
        gap: 8px;
        padding: 12px;
        background: #fff;
        border-radius: 8px;
        margin: 16px 0;
        font-size: 13px;
        color: #666;
        
        .el-icon {
          color: #409eff;
          margin-top: 2px;
        }
      }
      
      .call-controls {
        display: flex;
        justify-content: center;
        gap: 24px;
        margin-top: 16px;
      }
    }
  }
  
  .action-buttons {
    margin-top: auto;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
}

// 动画
@keyframes pulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.1); opacity: 0.8; }
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

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

.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  
  .chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #eee;
    font-weight: 500;
    
    .turn-count {
      font-size: 13px;
      color: #666;
      font-weight: normal;
    }
  }
  
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    
    .message {
      margin-bottom: 16px;
      
      &.mine {
        display: flex;
        flex-direction: row-reverse;
        
        .message-content {
          align-items: flex-end;
          
          .message-body {
            background: #667eea;
            color: #fff;
          }
        }
      }
      
      &.other {
        display: flex;
        
        .message-content {
          .message-body {
            background: #f0f2f5;
          }
        }
      }
      
      &.system {
        .system-message {
          text-align: center;
          font-size: 13px;
          color: #999;
          padding: 8px 0;
        }
      }
      
      .message-avatar {
        margin: 0 12px;
      }
      
      .message-content {
        display: flex;
        flex-direction: column;
        max-width: 60%;
        
        .message-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;
          
          .sender-name {
            font-size: 13px;
            font-weight: 500;
          }
          
          .message-time {
            font-size: 12px;
            color: #999;
          }
        }
        
        .message-body {
          padding: 12px 16px;
          border-radius: 12px;
          line-height: 1.5;
        }
      }
    }
    
    .empty-chat {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  .chat-input {
    display: flex;
    gap: 12px;
    padding: 16px 24px;
    border-top: 1px solid #eee;
    
    .el-textarea {
      flex: 1;
    }
    
    .el-button {
      align-self: flex-end;
    }
  }
}
</style>
