<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast, showLoadingToast, closeToast } from 'vant';
import { useConnectionStore } from '../stores/connection';

const route = useRoute();
const router = useRouter();
const connectionStore = useConnectionStore();

// State
const token = ref<string>('');
const isValidating = ref<boolean>(true);
const isValid = ref<boolean>(false);
const isSubmitting = ref<boolean>(false);
const userName = ref<string>('');
const department = ref<string>('技术部');
const errorMessage = ref<string>('');

// API base URL - use LAN IP for mobile access
const apiUrl = import.meta.env.VITE_API_URL || 'http://192.168.1.5:3000';

// Computed
const canSubmit = computed(() => {
  return userName.value.trim().length > 0 && department.value.trim().length > 0;
});

// Validate token on mount
onMounted(async () => {
  token.value = (route.query.token as string) || '';

  if (!token.value) {
    errorMessage.value = '无效的登录链接';
    isValidating.value = false;
    return;
  }

  await validateToken();
});

async function validateToken() {
  try {
    const response = await fetch(`${apiUrl}/api/scan/validate/${token.value}`);
    const result = await response.json();

    if (!result.success) {
      errorMessage.value = result.error || '验证失败';
      isValid.value = false;
    } else if (!result.data.valid) {
      errorMessage.value = result.data.status === 'expired'
        ? '二维码已过期，请重新扫描'
        : '无效的二维码';
      isValid.value = false;
    } else if (result.data.status === 'confirmed') {
      errorMessage.value = '此二维码已被使用';
      isValid.value = false;
    } else {
      isValid.value = true;
      // Mark as scanned
      await markScanned();
    }
  } catch (err) {
    errorMessage.value = '网络错误，请重试';
    isValid.value = false;
  } finally {
    isValidating.value = false;
  }
}

async function markScanned() {
  try {
    await fetch(`${apiUrl}/api/scan/scanned`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ scanToken: token.value }),
    });
  } catch (err) {
    console.error('Failed to mark scanned:', err);
  }
}

async function handleSubmit() {
  if (!canSubmit.value || isSubmitting.value) return;

  isSubmitting.value = true;
  showLoadingToast({ message: '登录中...', forbidClick: true });

  try {
    const response = await fetch(`${apiUrl}/api/scan/confirm`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        scanToken: token.value,
        userName: userName.value.trim(),
        department: department.value.trim(),
      }),
    });

    const result = await response.json();
    closeToast();

    if (result.success) {
      // Set user info in connection store
      const userId = result.data?.sessionToken || `user_${Date.now()}`;
      connectionStore.setUser(userId, userName.value.trim(), department.value.trim());

      showToast({ message: '登录成功！', type: 'success' });

      // Redirect to vote page
      router.push('/vote');
    } else {
      showToast({ message: result.error || '登录失败', type: 'fail' });
    }
  } catch (err) {
    closeToast();
    showToast({ message: '网络错误，请重试', type: 'fail' });
  } finally {
    isSubmitting.value = false;
  }
}
</script>

<template>
  <div class="scan-login-view safe-area-top safe-area-bottom">
    <!-- Header -->
    <div class="header">
      <h1 class="title">扫码登录</h1>
      <p class="subtitle">年会互动系统</p>
    </div>

    <!-- Loading state -->
    <div v-if="isValidating" class="loading-state">
      <van-loading type="spinner" color="#c41230" size="48px" />
      <p>正在验证...</p>
    </div>

    <!-- Error state -->
    <div v-else-if="!isValid" class="error-state">
      <van-icon name="warning-o" size="64" color="#c41230" />
      <p class="error-text">{{ errorMessage }}</p>
      <van-button type="primary" round @click="$router.push('/')">
        返回首页
      </van-button>
    </div>

    <!-- Login form -->
    <div v-else class="form-section">
      <div class="form-card">
        <p class="form-hint">请填写您的信息完成登录</p>

        <van-cell-group inset>
          <van-field
            v-model="userName"
            label="姓名"
            placeholder="请输入您的姓名"
            :rules="[{ required: true, message: '请输入姓名' }]"
            maxlength="20"
          />
          <van-field
            v-model="department"
            label="部门"
            placeholder="请输入您的部门"
            :rules="[{ required: true, message: '请输入部门' }]"
            maxlength="20"
          />
        </van-cell-group>

        <div class="button-wrapper">
          <van-button
            type="primary"
            block
            round
            :disabled="!canSubmit"
            :loading="isSubmitting"
            loading-text="登录中..."
            @click="handleSubmit"
          >
            确认登录
          </van-button>
        </div>
      </div>
    </div>

    <!-- Footer -->
    <div class="footer">
      <p>© 2026 公司年会</p>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@use '../assets/styles/variables.scss' as *;

.scan-login-view {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #fff5f5 0%, #fef8f0 50%, #ffffff 100%);
}

.header {
  text-align: center;
  padding: 48px 24px 24px;

  .title {
    font-size: 28px;
    color: $color-primary;
    font-weight: bold;
    margin-bottom: 8px;
  }

  .subtitle {
    font-size: 14px;
    color: $color-text-secondary;
  }
}

.loading-state,
.error-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 24px;
}

.error-text {
  font-size: 16px;
  color: $color-primary;
  text-align: center;
}

.form-section {
  flex: 1;
  padding: 24px;
}

.form-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.form-hint {
  text-align: center;
  color: $color-text-secondary;
  font-size: 14px;
  margin-bottom: 24px;
}

.button-wrapper {
  margin-top: 32px;

  :deep(.van-button--primary) {
    background: linear-gradient(135deg, $color-primary-light 0%, $color-primary 100%);
    border: none;
  }
}

.footer {
  text-align: center;
  padding: 16px;
  color: $color-text-muted;
  font-size: 12px;
}
</style>
