<script setup lang="ts">
import { onMounted, ref } from "vue";
import { api, saveToken } from "../services/api";
import type { UserProfile } from "../types/api";

const emit = defineEmits<{
  loggedIn: [user: UserProfile];
}>();

const phone = ref("");
const code = ref("");
const captchaId = ref("");
const captchaCode = ref("");
const captchaImage = ref("");
const loading = ref(false);
const captchaLoading = ref(false);
const message = ref("请先完成图形验证码，再获取短信验证码。");
const errorDialog = ref("");

onMounted(() => {
  void loadCaptcha();
});

async function loadCaptcha() {
  captchaLoading.value = true;
  try {
    const result = await api.captcha();
    captchaId.value = result.captchaId;
    captchaImage.value = result.imageBase64;
    captchaCode.value = "";
  } catch (error) {
    message.value = error instanceof Error ? error.message : "图形验证码加载失败";
  } finally {
    captchaLoading.value = false;
  }
}

async function sendCode() {
  if (!captchaId.value || captchaCode.value.length < 4) {
    showError("请先输入图形验证码");
    return;
  }
  loading.value = true;
  message.value = "";
  try {
    await api.sendSms(phone.value, captchaId.value, captchaCode.value);
    message.value = "短信验证码已发送，请查收。";
    await loadCaptcha();
  } catch (error) {
    showError(error instanceof Error ? error.message : "发送失败");
    await loadCaptcha();
  } finally {
    loading.value = false;
  }
}

async function login() {
  loading.value = true;
  message.value = "";
  try {
    const result = await api.login(phone.value, code.value);
    saveToken(result.token);
    emit("loggedIn", result.user);
  } catch (error) {
    message.value = error instanceof Error ? error.message : "登录失败";
  } finally {
    loading.value = false;
  }
}

function showError(text: string) {
  message.value = text;
  errorDialog.value = text;
}
</script>

<template>
  <section class="login-panel">
    <div class="brand-mark">答</div>
    <h1>大本营答疑助手</h1>
    <p>有问题随时问，帮你快速找到答案。</p>

    <label>
      手机号
      <input v-model="phone" inputmode="numeric" maxlength="11" placeholder="请输入手机号" />
    </label>

    <label>
      图形验证码
      <div class="captcha-row">
        <input v-model="captchaCode" inputmode="text" maxlength="8" placeholder="请输入图形验证码" />
        <button type="button" class="captcha-image" :disabled="captchaLoading" @click="loadCaptcha">
          <img v-if="captchaImage" :src="captchaImage" alt="图形验证码" />
          <span v-else>{{ captchaLoading ? "加载中" : "刷新" }}</span>
        </button>
      </div>
    </label>

    <label>
      短信验证码
      <div class="code-row">
        <input v-model="code" inputmode="numeric" maxlength="8" placeholder="请输入短信验证码" />
        <button
          type="button"
          class="secondary"
          :disabled="loading || phone.length < 11 || captchaCode.length < 4"
          @click="sendCode"
        >
          发送
        </button>
      </div>
    </label>

    <button type="button" class="primary" :disabled="loading || phone.length < 11 || code.length < 4" @click="login">
      {{ loading ? "处理中..." : "立即进入" }}
    </button>
    <div class="form-tip">{{ message }}</div>

    <div v-if="errorDialog" class="dialog-mask" role="alertdialog" aria-modal="true" aria-labelledby="login-error-title">
      <div class="dialog-box">
        <strong id="login-error-title">无法发送验证码</strong>
        <p>{{ errorDialog }}</p>
        <button type="button" class="primary" @click="errorDialog = ''">知道了</button>
      </div>
    </div>
  </section>
</template>
