<template>
  <main class="login-shell">
    <section class="login-panel" :aria-label="isRegisterMode ? '注册' : '登录'">
      <img class="brand-mark" src="/logo.png" alt="网盘管理" aria-hidden="true" />
      <h1>网盘管理</h1>
      <p>
        {{ isRegisterMode ? '创建新账号后即可返回登录，开始管理你的网盘资源。' : 'Welcome home' }}
      </p>

      <div class="auth-switch">
        <button
          type="button"
          class="switch-chip"
          :class="{ active: !isRegisterMode }"
          @click="switchMode(false)"
        >
          登录
        </button>
        <button
          type="button"
          class="switch-chip"
          :class="{ active: isRegisterMode }"
          @click="switchMode(true)"
        >
          注册
        </button>
      </div>

      <form v-if="!isRegisterMode" class="login-form" @submit.prevent="handleLoginSubmit">
        <label>
          <span>登录账号</span>
          <input
            v-model="loginForm.username"
            type="text"
            autocomplete="username"
            placeholder="请输入账号"
          />
        </label>

        <label>
          <span>访问口令</span>
          <input
            v-model="loginForm.password"
            type="password"
            autocomplete="current-password"
            placeholder="请输入口令"
          />
        </label>

        <label>
          <span>图形验证码</span>
          <div class="captcha-row">
            <input
              v-model="loginForm.captchaInput"
              type="text"
              autocomplete="off"
              placeholder="输入右侧字符"
              maxlength="6"
            />
            <canvas
              ref="canvasRef"
              width="136"
              height="46"
              title="点击刷新验证码"
              @click="refreshCaptcha"
            />
          </div>
        </label>

        <button type="submit" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
        <div v-if="props.notice && !message" class="form-message warning" role="status">{{ props.notice }}</div>
        <div class="form-message" role="alert">{{ message }}</div>
      </form>

      <form v-else class="login-form register-form" @submit.prevent="handleRegisterSubmit">
        <label>
          <span>注册账号</span>
          <input
            v-model="registerForm.username"
            type="text"
            autocomplete="username"
            placeholder="请输入账号"
          />
        </label>

        <label>
          <span>邮箱（选填）</span>
          <input
            v-model="registerForm.email"
            type="email"
            autocomplete="email"
            placeholder="请输入邮箱"
          />
        </label>

        <label>
          <span>手机号（选填）</span>
          <input
            v-model="registerForm.phone"
            type="tel"
            autocomplete="tel"
            placeholder="请输入手机号"
          />
        </label>

        <label>
          <span>登录密码</span>
          <input
            v-model="registerForm.password"
            type="password"
            autocomplete="new-password"
            placeholder="请输入密码"
          />
        </label>

        <label>
          <span>确认密码</span>
          <input
            v-model="registerForm.confirmPassword"
            type="password"
            autocomplete="new-password"
            placeholder="请再次输入密码"
          />
        </label>

        <button type="submit" :disabled="loading">
          {{ loading ? '注册中...' : '立即注册' }}
        </button>
        <div class="form-message success" role="status">{{ registerSuccessMessage }}</div>
        <div class="form-message" role="alert">{{ message }}</div>
      </form>
    </section>
    <footer class="page-footer">
      <a href="https://beian.miit.gov.cn/" target="_blank" rel="noopener noreferrer">Copyright © 2013 - 2026 浙ICP备2024131314号-3</a>
    </footer>
  </main>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { login, register } from '../api'
import { drawCaptcha, generateCaptcha } from '../utils/captcha'

const props = defineProps({
  notice: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['success', 'clear-notice'])

const loading = ref(false)
const message = ref('')
const registerSuccessMessage = ref('')
const isRegisterMode = ref(false)
const canvasRef = ref(null)
const captchaCode = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  captchaInput: '',
})

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
})

function resetMessage() {
  message.value = ''
  registerSuccessMessage.value = ''
}

function switchMode(registerMode) {
  isRegisterMode.value = registerMode
  resetMessage()
  // 清除父组件传递的 notice
  if (props.notice) {
    emit('clear-notice')
  }
  if (!registerMode) {
    refreshCaptcha()
  }
}

function refreshCaptcha() {
  captchaCode.value = generateCaptcha()
  nextTick(() => drawCaptcha(canvasRef.value, captchaCode.value))
}

async function handleLoginSubmit() {
  resetMessage()

  if (!loginForm.username.trim()) {
    message.value = '请输入登录账号'
    return
  }

  if (!loginForm.password.trim()) {
    message.value = '请输入访问口令'
    return
  }

  if (loginForm.captchaInput.trim().toUpperCase() !== captchaCode.value) {
    message.value = '验证码不正确，请重新输入'
    loginForm.captchaInput = ''
    refreshCaptcha()
    return
  }

  loading.value = true

  try {
    const result = await login({
      username: loginForm.username.trim(),
      password: loginForm.password,
    })

    if (result?.code !== 200 || !result?.data?.token) {
      throw new Error(result?.message || '登录失败')
    }

    emit('success', {
      ...result.data,
      username: result?.data?.username || loginForm.username.trim(),
    })
    loginForm.captchaInput = ''
  } catch (error) {
    console.error('登录失败:', error)
    message.value = error?.message || '登录失败，请稍后重试'
    loginForm.captchaInput = ''
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

async function handleRegisterSubmit() {
  resetMessage()

  if (!registerForm.username.trim()) {
    message.value = '请输入注册账号'
    return
  }

  if (!registerForm.password.trim()) {
    message.value = '请输入登录密码'
    return
  }

  if (registerForm.password !== registerForm.confirmPassword) {
    message.value = '两次输入的密码不一致'
    return
  }

  loading.value = true

  try {
    const result = await register({
      username: registerForm.username.trim(),
      password: registerForm.password,
      email: registerForm.email.trim(),
      phone: registerForm.phone.trim(),
    })

    if (result?.code !== 200) {
      throw new Error(result?.message || '注册失败')
    }

    registerSuccessMessage.value = result?.message || '注册成功，请返回登录'
    loginForm.username = registerForm.username.trim()
    loginForm.password = registerForm.password
    registerForm.username = ''
    registerForm.password = ''
    registerForm.confirmPassword = ''
    registerForm.email = ''
    registerForm.phone = ''

    window.setTimeout(() => {
      switchMode(false)
    }, 800)
  } catch (error) {
    console.error('注册失败:', error)
    message.value = error?.message || '注册失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.page-footer {
  position: fixed;
  bottom: 8px;
  left: 0;
  right: 0;
  text-align: center;
  z-index: 10;
}

.page-footer a {
  color: rgba(223, 215, 255, 0.45);
  font-size: 12px;
  text-decoration: none;
  transition: color 0.2s ease;
}

.page-footer a:hover {
  color: rgba(223, 215, 255, 0.8);
}
</style>
