<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <img src="@/assets/logo.svg" alt="logo" class="login-logo" />
        <h1 class="login-title">机器任务管理后台</h1>
        <p class="login-subtitle">宝时智能仓管理系统</p>
      </div>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        size="large"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
            :prefix-icon="Lock"
          />
        </el-form-item>
        <el-form-item>
          <div class="entry-mode-wrap">
            <span class="entry-mode-label">进入端口</span>
            <el-radio-group v-model="entryMode">
              <el-radio-button
                v-for="item in availableEntryModes"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-btn"
            @click="handleLogin"
          >
            登 录
          </el-button>
        </el-form-item>
      </el-form>

      <el-divider>或</el-divider>

      <el-button text type="info" class="token-link" @click="tokenDialogVisible = true">
        手动设置 Token
      </el-button>
    </div>

    <el-dialog v-model="tokenDialogVisible" title="手动设置 Token" width="420px" destroy-on-close>
      <el-input
        v-model="manualToken"
        type="textarea"
        :rows="3"
        placeholder="粘贴已有的 Token"
      />
      <template #footer>
        <el-button @click="tokenDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSetToken">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/user'
import type { EntryMode } from '@/stores/user'
import { Lock, User } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { computed, reactive, ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

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

const rules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const tokenDialogVisible = ref(false)
const manualToken = ref('')
const allEntryModes: Array<{ value: EntryMode; label: string }> = [
  { value: 'ops', label: '运维端' },
  { value: 'monitor', label: '监控端' },
]
const envEntryModes = (import.meta.env.VITE_ENTRY_OPTIONS as string | undefined) || 'ops,monitor'
const parsedEntryModes = envEntryModes.split(',').map((item) => item.trim()).filter((item) => item === 'ops' || item === 'monitor') as EntryMode[]
const availableEntryModes = computed(() => {
  const modeSet = new Set(parsedEntryModes.length ? parsedEntryModes : ['ops', 'monitor'])
  return allEntryModes.filter((item) => modeSet.has(item.value))
})
const entryMode = ref<EntryMode>(userStore.entryMode)

watchEffect(() => {
  if (!availableEntryModes.value.some((item) => item.value === entryMode.value)) {
    entryMode.value = availableEntryModes.value[0]?.value ?? 'ops'
  }
})

function handleSetToken() {
  const token = manualToken.value.trim()
  if (!token) {
    ElMessage.warning('Token 不能为空')
    return
  }
  userStore.setEntryMode(entryMode.value)
  localStorage.setItem('token', token)
  tokenDialogVisible.value = false
  ElMessage.success('Token 已设置')
  router.push('/')
}

async function handleLogin() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  loading.value = true
  try {
    userStore.setEntryMode(entryMode.value)
    await userStore.login(form.username, form.password)
    ElMessage.success('登录成功')
    router.push('/')
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : '登录失败'
    ElMessage.error(msg)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-card {
  width: 400px;
  max-width: calc(100vw - 32px);
  padding: 40px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
}

@media (max-width: 480px) {
  .login-card {
    padding: 28px 20px;
  }

  .login-title {
    font-size: 19px;
  }
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.login-logo {
  width: 56px;
  height: 56px;
  margin-bottom: 12px;
}

.login-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px;
}

.login-subtitle {
  font-size: 13px;
  color: #909399;
  margin: 0;
}

.login-btn {
  width: 100%;
}

.token-link {
  width: 100%;
  font-size: 13px;
}

.entry-mode-wrap {
  width: 100%;
}

.entry-mode-label {
  display: block;
  margin-bottom: 8px;
  font-size: 13px;
  color: #606266;
}
</style>
