<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, UploadFilled, ArrowLeft } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadFile, UploadUserFile } from 'element-plus'
import { candidateApi } from '@/api'

const router = useRouter()

// 表单数据
const formRef = ref<FormInstance>()
const formData = reactive({
  name: '',
})
const fileList = ref<UploadUserFile[]>([])
const uploading = ref(false)

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入您的姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度为 2-20 个字符', trigger: 'blur' },
  ],
}

// 文件变化处理
function handleFileChange(_file: UploadFile, files: UploadUserFile[]) {
  // 只保留最后一个文件
  fileList.value = files.slice(-1)
}

// 文件上传前验证
function beforeUpload(file: File) {
  const allowedTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  ]
  const isAllowedType = allowedTypes.includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isAllowedType) {
    ElMessage.error('只支持 PDF、DOC、DOCX 格式的文件')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB')
    return false
  }
  return true
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    if (fileList.value.length === 0) {
      ElMessage.error('请上传您的简历')
      return
    }

    uploading.value = true
    const file = fileList.value[0].raw as File

    const response = await candidateApi.submit(formData.name, file)

    // 存储 session 信息
    sessionStorage.setItem('sessionId', response.data.sessionId)
    sessionStorage.setItem('fileId', response.data.fileId)
    sessionStorage.setItem('candidateName', formData.name)

    ElMessage.success('信息提交成功')
    router.push('/call')
  } catch (error) {
    console.error('Submit error:', error)
  } finally {
    uploading.value = false
  }
}
</script>

<template>
  <div class="info-page w-full max-w-lg">
    <!-- 标题 -->
    <div class="text-center mb-8">
      <h1 class="text-2xl font-bold text-gray-800 mb-2">填写基本信息</h1>
      <p class="text-gray-500">请填写您的姓名并上传简历</p>
    </div>

    <!-- 表单 -->
    <div class="bg-white rounded-xl p-8 shadow-sm">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="top"
        size="large"
      >
        <!-- 姓名 -->
        <el-form-item label="您的姓名" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入您的姓名"
            :prefix-icon="User"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <!-- 简历上传 -->
        <el-form-item label="上传简历" required>
          <el-upload
            v-model:file-list="fileList"
            class="w-full"
            drag
            :auto-upload="false"
            :limit="1"
            accept=".pdf,.doc,.docx"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
          >
            <div class="py-8">
              <el-icon class="text-4xl text-gray-400 mb-4"><UploadFilled /></el-icon>
              <div class="text-gray-600">
                将文件拖到此处，或 <span class="text-blue-500">点击上传</span>
              </div>
              <div class="text-gray-400 text-sm mt-2">
                支持 PDF、DOC、DOCX 格式，大小不超过 10MB
              </div>
            </div>
          </el-upload>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item class="mb-0 mt-6">
          <el-button
            type="primary"
            class="w-full h-12"
            :loading="uploading"
            @click="handleSubmit"
          >
            {{ uploading ? '正在处理...' : '提交并开始面试' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 返回按钮 -->
    <div class="text-center mt-6">
      <el-button text @click="router.push('/')">
        <el-icon class="mr-1"><ArrowLeft /></el-icon>
        返回上一步
      </el-button>
    </div>
  </div>
</template>

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

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

:deep(.el-upload-dragger) {
  border: 2px dashed #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #3b82f6;
}
</style>
