<template>
  <div class="register-page">
    <div class="container mx-auto px-4 py-8">
      <div class="max-w-md mx-auto card">
        <div class="text-center mb-8">
          <h1 class="text-3xl font-bold text-white mb-2">加入情绪博物馆</h1>
          <p class="text-white/80">只需几步，开启你的情绪探索之旅</p>
        </div>

        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          label-width="0"
          @submit.prevent="handleRegister"
        >
          <el-form-item prop="nickname">
            <el-input
              v-model="registerForm.nickname"
              placeholder="请输入昵称"
              :prefix-icon="Avatar"
              size="large"
              clearable
            />
          </el-form-item>

          <el-form-item prop="account">
            <el-input
              v-model="registerForm.account"
              placeholder="请输入账号（4-20位字母数字下划线）"
              :prefix-icon="User"
              size="large"
              clearable
              @blur="checkAccountExists"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码（6-20位）"
              :prefix-icon="Lock"
              size="large"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              :prefix-icon="Lock"
              size="large"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item prop="captcha">
            <div class="flex gap-3">
              <el-input
                v-model="registerForm.captcha"
                placeholder="请输入验证码"
                :prefix-icon="Key"
                size="large"
                clearable
                class="flex-1"
              />
              <div class="captcha-container" @click="refreshCaptcha">
                <img
                  v-if="captchaImage"
                  :src="captchaImage"
                  alt="验证码"
                  class="captcha-image"
                />
                <div v-else class="captcha-loading">
                  <el-icon class="is-loading"><Loading /></el-icon>
                </div>
              </div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="w-full register-btn"
              :loading="loading"
              @click="handleRegister"
            >
              {{ loading ? '注册中...' : '立即注册' }}
            </el-button>
          </el-form-item>
        </el-form>

        <div class="text-center mt-6">
          <span class="text-white/70">已有账号？</span>
          <router-link to="/login" class="text-white font-medium hover:underline ml-1">
            立即登录
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import {
  User,
  UserFilled,
  Avatar,
  Message,
  Phone,
  Lock,
  Key,
  Loading
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import AuthService from '@/services/auth'
import { envConfig } from '@/config/env'
import type { RegisterRequest } from '@/types/auth'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const registerFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 验证码相关
const captchaImage = ref('')
const captchaKey = ref('')

// 注册表单数据（简化版）
const registerForm = reactive({
  account: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  captcha: '',
  captchaKey: ''
})

// 自定义验证规则
const validateAccount = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入账号'))
    return
  }
  if (!/^[a-zA-Z0-9_]{4,20}$/.test(value)) {
    callback(new Error('账号只能包含字母、数字和下划线，长度4-20位'))
    return
  }
  // 账号唯一性校验建议在@blur时单独提示，不在rules中异步校验
  callback()
}

const validatePassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入密码'))
    return
  }
  if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度必须在6-20位之间'))
    return
  }
  callback()
}

const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请再次输入密码'))
    return
  }
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
    return
  }
  callback()
}

// 移除了邮箱和手机号验证，简化注册流程

// 表单验证规则（简化版）
const registerRules: FormRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 20, message: '昵称长度必须在1-20位之间', trigger: 'blur' }
  ],
  account: [{ validator: validateAccount, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度不正确', trigger: 'blur' }
  ]
}

/**
 * 获取验证码
 */
const getCaptcha = async () => {
  try {
    const response = await AuthService.getCaptcha()
    // 后端返回的数据已经包含了 data:image/png;base64, 前缀，直接使用
    captchaImage.value = response.captchaImage
    captchaKey.value = response.captchaKey
    registerForm.captchaKey = response.captchaKey
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败')
  }
}

/**
 * 刷新验证码
 */
const refreshCaptcha = () => {
  registerForm.captcha = ''
  getCaptcha()
}

/**
 * 检查账号是否存在
 */
const checkAccountExists = async () => {
  if (!registerForm.account || !/^[a-zA-Z0-9_]{4,20}$/.test(registerForm.account)) {
    return
  }

  try {
    const exists = await AuthService.checkAccountExists(registerForm.account)
    if (exists) {
      ElMessage.warning('该账号已存在')
    }
  } catch (error) {
    console.error('检查账号失败:', error)
  }
}

// 移除了邮箱和手机号检查方法，简化注册流程

/**
 * 处理注册
 */
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    console.log('开始注册流程...')
    console.log('注册表单数据:', registerForm)

    // 表单验证
    await registerFormRef.value.validate()
    console.log('表单验证通过')

    loading.value = true

    // 构造注册请求数据
    const registerData = {
      account: registerForm.account,
      password: registerForm.password,
      confirmPassword: registerForm.confirmPassword,
      username: registerForm.nickname, // 使用昵称作为用户名
      nickname: registerForm.nickname,
      email: '', // 暂时为空，后续在个人页面完善
      phone: '', // 暂时为空，后续在个人页面完善
      captcha: registerForm.captcha,
      captchaKey: registerForm.captchaKey
    }

    // 调用注册接口
    console.log('调用注册接口...')
    const success = await authStore.register(registerData)
    console.log('注册结果:', success)

    if (success) {
      // 注册成功，跳转到首页
      console.log('注册成功，跳转到首页')
      ElMessage.success('注册成功，欢迎加入情绪博物馆！')
      router.push('/')
    } else {
      // 注册失败，刷新验证码
      console.log('注册失败，刷新验证码')
      refreshCaptcha()
    }
  } catch (error: any) {
    console.error('注册过程中发生错误:', error)

    // 根据错误类型显示不同的提示
    let errorMessage = '注册失败，请稍后重试'
    if (error.message) {
      if (error.message.includes('账号已存在')) {
        errorMessage = '该账号已被注册，请更换账号或直接登录'
      } else if (error.message.includes('邮箱已存在')) {
        errorMessage = '该邮箱已被注册，请更换邮箱或直接登录'
      } else if (error.message.includes('手机号已存在')) {
        errorMessage = '该手机号已被注册，请更换手机号或直接登录'
      } else if (error.message.includes('验证码')) {
        errorMessage = '验证码错误，请重新输入'
      } else {
        errorMessage = error.message
      }
    }

    ElMessage.error(errorMessage)
    // 刷新验证码
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取验证码
onMounted(() => {
  getCaptcha()
})
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-attachment: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem 1rem;
}

.container {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 24px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
  padding: 3rem 2.5rem;
  width: 100%;
  max-width: 420px;
}

.card {
  background: transparent;
  border: none;
  box-shadow: none;
}

.captcha-container {
  width: 140px;
  height: 48px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.captcha-container:hover {
  border-color: rgba(255, 255, 255, 0.5);
  background: rgba(255, 255, 255, 0.15);
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10px;
}

.captcha-loading {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
}

:deep(.el-input--large .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  box-shadow: none;
  transition: all 0.3s ease;
  padding: 0 16px;
  height: 48px;
}

:deep(.el-input--large .el-input__wrapper:hover) {
  border-color: rgba(255, 255, 255, 0.4);
  background: rgba(255, 255, 255, 0.15);
}

:deep(.el-input--large .el-input__wrapper.is-focus) {
  border-color: rgba(255, 255, 255, 0.6);
  background: rgba(255, 255, 255, 0.2);
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.1);
}

:deep(.el-input--large .el-input__inner) {
  color: white;
  font-size: 16px;
}

:deep(.el-input--large .el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

:deep(.el-input--large .el-input__prefix) {
  color: rgba(255, 255, 255, 0.7);
}

:deep(.el-input--large .el-input__suffix) {
  color: rgba(255, 255, 255, 0.7);
}

.register-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  border: none;
  border-radius: 12px;
  font-weight: 600;
  font-size: 16px;
  height: 48px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
}

:deep(.register-btn:hover) {
  background: linear-gradient(135deg, #ff5252 0%, #d63031 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4);
}

:deep(.register-btn:active) {
  transform: translateY(0);
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-form-item__error) {
  color: #ffcdd2;
  background: rgba(255, 107, 107, 0.1);
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .register-page {
    padding: 1rem 0.5rem;
  }

  .container {
    padding: 2rem 1.5rem;
    border-radius: 20px;
    max-width: 100%;
  }

  .captcha-container {
    width: 120px;
    height: 44px;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.container {
  animation: fadeInUp 0.6s ease-out;
}
</style>