<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { candidateApi } from '@/api'

const router = useRouter()

// 表单数据
const candidateName = ref('')
const resumeFile = ref<File | null>(null)
const isUploading = ref(false)
const uploadedFileId = ref('')

// 面试模式：voice（语音）或 text（文字）
const interviewMode = ref<'voice' | 'text'>('voice')

// 调试信息
const showDebug = ref(true)
const debugInfo = ref<any>(null)

// 处理文件选择
function handleFileChange(file: any) {
  if (file.raw) {
    const rawFile = file.raw as File
    // 验证文件类型
    if (!rawFile.type.includes('pdf')) {
      ElMessage.error('请上传 PDF 格式的简历')
      return false
    }
    // 验证文件大小（最大 10MB）
    if (rawFile.size > 10 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过 10MB')
      return false
    }
    resumeFile.value = rawFile
  }
  return false // 阻止自动上传
}

// 移除文件
function handleFileRemove() {
  resumeFile.value = null
  uploadedFileId.value = ''
}

// 开始面试
async function startInterview() {
  // 验证姓名
  if (!candidateName.value.trim()) {
    ElMessage.error('请输入您的姓名')
    return
  }

  // 验证简历
  if (!resumeFile.value) {
    ElMessage.error('请上传您的简历')
    return
  }

  isUploading.value = true
  debugInfo.value = { status: '开始初始化...', timestamp: new Date().toISOString() }

  try {
    // 调用初始化面试 API（工作流 A）
    ElMessage.info('正在初始化面试，请稍候...')
    
    debugInfo.value = { 
      ...debugInfo.value, 
      step: '调用 initInterview API',
      inputName: candidateName.value.trim(),
      fileName: resumeFile.value.name,
      fileSize: resumeFile.value.size
    }
    
    const response = await candidateApi.initInterview(
      candidateName.value.trim(),
      resumeFile.value
    )
    
    // 记录完整响应
    debugInfo.value = {
      ...debugInfo.value,
      step: 'API 响应成功',
      fullResponse: response,
      responseData: response.data,
      sessionId: response.data?.sessionId,
      name: response.data?.name,
      debugUrl: response.data?.debugUrl,
      workflowResponse: response.data?.workflowResponse
    }
    
    const { sessionId, name } = response.data
    
    if (!sessionId) {
      debugInfo.value.error = 'sessionId 为空!'
      ElMessage.error('初始化失败：sessionId 为空')
      return
    }
    
    ElMessage.success('面试初始化成功')

    // 保存信息到 sessionStorage，供 call 页面使用
    sessionStorage.setItem('candidateName', name)
    sessionStorage.setItem('sessionId', sessionId)
    sessionStorage.setItem('interviewMode', interviewMode.value)
    // 保存调试信息
    sessionStorage.setItem('initDebugInfo', JSON.stringify(debugInfo.value))

    // 跳转到通话页
    router.push('/call')
  } catch (error: any) {
    console.error('Init interview error:', error)
    debugInfo.value = {
      ...debugInfo.value,
      step: 'API 错误',
      error: error.message,
      errorResponse: error.response?.data,
      errorStatus: error.response?.status
    }
    ElMessage.error(error.message || '初始化失败，请重试')
  } finally {
    isUploading.value = false
  }
}
</script>

<template>
  <div class="welcome-page w-full max-w-lg text-center">
    <!-- Logo 区域 -->
    <div class="mb-6">
      <div class="w-20 h-20 mx-auto bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center shadow-lg">
        <el-icon :size="40" class="text-white"><Microphone /></el-icon>
      </div>
    </div>

    <!-- 标题 -->
    <h1 class="text-2xl font-bold text-gray-800 mb-2">
      欢迎参加 AI 面试
    </h1>
    <p class="text-gray-500 text-sm mb-6">
      请填写基本信息并上传简历
    </p>

    <!-- 信息收集表单 -->
    <div class="bg-white rounded-xl p-6 mb-6 shadow-sm text-left">
      <!-- 姓名输入 -->
      <div class="mb-4">
        <label class="block text-sm font-medium text-gray-700 mb-2">
          您的姓名 <span class="text-red-500">*</span>
        </label>
        <el-input
          v-model="candidateName"
          placeholder="请输入您的真实姓名"
          size="large"
          :disabled="isUploading"
        />
      </div>

      <!-- 面试模式选择 -->
      <div class="mb-4">
        <label class="block text-sm font-medium text-gray-700 mb-2">
          面试模式 <span class="text-red-500">*</span>
        </label>
        <div class="grid grid-cols-2 gap-3">
          <div
            class="mode-card p-4 rounded-lg border-2 cursor-pointer transition-all"
            :class="interviewMode === 'voice' ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'"
            @click="interviewMode = 'voice'"
          >
            <div class="flex items-center gap-2 mb-1">
              <el-icon :size="20" :class="interviewMode === 'voice' ? 'text-blue-500' : 'text-gray-400'">
                <Microphone />
              </el-icon>
              <span class="font-medium" :class="interviewMode === 'voice' ? 'text-blue-600' : 'text-gray-700'">
                语音对话
              </span>
            </div>
            <p class="text-xs text-gray-500">通过语音与 AI 面试官交流</p>
          </div>
          <div
            class="mode-card p-4 rounded-lg border-2 cursor-pointer transition-all"
            :class="interviewMode === 'text' ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'"
            @click="interviewMode = 'text'"
          >
            <div class="flex items-center gap-2 mb-1">
              <el-icon :size="20" :class="interviewMode === 'text' ? 'text-blue-500' : 'text-gray-400'">
                <ChatLineSquare />
              </el-icon>
              <span class="font-medium" :class="interviewMode === 'text' ? 'text-blue-600' : 'text-gray-700'">
                文字对话
              </span>
            </div>
            <p class="text-xs text-gray-500">通过文字输入与 AI 面试官交流</p>
          </div>
        </div>
      </div>

      <!-- 简历上传 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          简历文件 <span class="text-red-500">*</span>
        </label>
        <el-upload
          class="resume-upload"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :limit="1"
          accept=".pdf"
          :disabled="isUploading"
        >
          <div v-if="!resumeFile" class="py-4">
            <el-icon class="text-4xl text-gray-400 mb-2"><UploadFilled /></el-icon>
            <div class="text-gray-500 text-sm">
              点击或拖拽上传简历
            </div>
            <div class="text-gray-400 text-xs mt-1">
              仅支持 PDF 格式，最大 10MB
            </div>
          </div>
          <div v-else class="py-4">
            <el-icon class="text-4xl text-green-500 mb-2"><Document /></el-icon>
            <div class="text-gray-700 text-sm">
              {{ resumeFile.name }}
            </div>
            <div class="text-gray-400 text-xs mt-1">
              {{ (resumeFile.size / 1024 / 1024).toFixed(2) }} MB
            </div>
          </div>
        </el-upload>
      </div>
    </div>

    <!-- 准备事项 -->
    <div class="bg-gray-50 rounded-xl p-4 mb-6 text-left">
      <h3 class="text-sm font-medium text-gray-700 mb-2">面试须知</h3>
      <ul class="space-y-1 text-gray-500 text-xs">
        <li class="flex items-center gap-2">
          <el-icon class="text-green-500"><CircleCheck /></el-icon>
          <span>确保网络稳定、环境安静</span>
        </li>
        <li class="flex items-center gap-2">
          <el-icon class="text-green-500"><CircleCheck /></el-icon>
          <span>面试时长约 15-20 分钟</span>
        </li>
        <li v-if="interviewMode === 'voice'" class="flex items-center gap-2">
          <el-icon class="text-green-500"><CircleCheck /></el-icon>
          <span>需要授权麦克风权限</span>
        </li>
        <li v-else class="flex items-center gap-2">
          <el-icon class="text-green-500"><CircleCheck /></el-icon>
          <span>请认真阅读问题并输入回答</span>
        </li>
      </ul>
    </div>

    <!-- 开始按钮 -->
    <el-button
      type="primary"
      size="large"
      class="w-full h-12 text-base"
      :loading="isUploading"
      :disabled="!candidateName.trim() || !resumeFile"
      @click="startInterview"
    >
      {{ isUploading ? '正在上传...' : '开始面试' }}
      <el-icon v-if="!isUploading" class="ml-2"><ArrowRight /></el-icon>
    </el-button>

    <!-- 底部提示 -->
    <p class="text-xs text-gray-400 mt-4">
      点击"开始面试"即表示您同意我们的隐私政策
    </p>

    <!-- 调试面板 -->
    <div v-if="showDebug" class="debug-panel mt-6">
      <div class="debug-header">
        <span>🔧 调试信息</span>
        <el-switch v-model="showDebug" size="small" />
      </div>
      <div v-if="debugInfo" class="debug-content">
        <pre>{{ JSON.stringify(debugInfo, null, 2) }}</pre>
      </div>
      <div v-else class="debug-empty">
        等待操作...
      </div>
    </div>
  </div>
</template>

<style scoped>
.welcome-page {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.resume-upload :deep(.el-upload-dragger) {
  padding: 10px;
  border-radius: 8px;
}

.resume-upload :deep(.el-upload-list) {
  display: none;
}

/* 调试面板 */
.debug-panel {
  background: #1e1e2d;
  border-radius: 12px;
  overflow: hidden;
  text-align: left;
}

.debug-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #2d2d3d;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

.debug-content {
  padding: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.debug-content pre {
  margin: 0;
  font-size: 12px;
  color: #a0f0a0;
  white-space: pre-wrap;
  word-break: break-all;
  font-family: 'Monaco', 'Consolas', monospace;
}

.debug-empty {
  padding: 20px;
  text-align: center;
  color: #666;
  font-size: 13px;
}
</style>
