<template>
  <div class="login-page">
    <h1>欢迎登录</h1>
    <div class="login-tabs">
      <div class="tab-item" :class="{ active: activeTab === 'account' }" @click="activeTab = 'account'">
        账号密码登录
      </div>
      <div class="tab-item" :class="{ active: activeTab === 'phone' }" @click="activeTab = 'phone'">
        手机号登录
      </div>
    </div>
    <el-form ref="formRef" :model="accountForm" :rules="rules" class="login-form">
      <template v-if="activeTab === 'account'">
        <el-form-item prop="username">
          <el-input v-model="accountForm.username" placeholder="请输入手机号或账号" size="large">
            <template #prefix>
              <div class="input-prefix">
                <el-icon :size="16">
                  <User />
                </el-icon>
                <span>账号</span>
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="accountForm.password" type="password" placeholder="请输入密码" size="large" show-password>
            <template #prefix>
              <div class="input-prefix">
                <el-icon :size="16">
                  <Lock />
                </el-icon>
                <span>密码</span>
              </div>
            </template>
          </el-input>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item>
          <el-input v-model="phoneForm.phone" placeholder="请输入手机号" size="large">
            <template #prefix>
              <div class="input-prefix">
                <el-icon :size="16">
                  <Iphone />
                </el-icon>
                <span>手机号</span>
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <div class="login-code">
            <el-input style="width: 60%;" v-model="phoneForm.code" placeholder="请输入验证码" size="large">
              <template #prefix>
                <div class="input-prefix">
                  <SvgIcon iconClass="protect" />
                  <span>验证码</span>
                </div>
              </template>
            </el-input>
            <el-button size="large" style="width: 30%; min-width: 100px;" type="primary" class="is-gradient"
              :disabled="isCountingDown" @click="handleGetCode">
              {{ isCountingDown ? `${countdown}s` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </template>
      <div class="form-end">
        <el-button size="large" style="width:100%" type="primary" class="is-gradient" :loading="loading" @click="handleLogin">立即登录</el-button>
        <div class="form-links">
          <div class="left-links">
            <span class="link-text">还没有账号？</span>
            <span class="link-btn" @click="handleRegister">立即注册</span>
          </div>
          <span class="link-btn" @click="handleForgot">忘记密码？</span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { User, Lock, Iphone } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

const emit = defineEmits<{
  (e: 'switch', component: 'register' | 'forgot'): void
}>()
type TabType = 'account' | 'phone'
const activeTab = ref<TabType>('account')
const isCountingDown = ref(false)
const countdown = ref(60)
let countdownTimer: ReturnType<typeof setInterval> | null = null
const formRef = ref<FormInstance>()
const loading = ref(false)
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const accountForm = reactive({
  username: 'admin',
  password: '123456'
})

const phoneForm = reactive({
  phone: '',
  code: ''
})


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

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

  loading.value = true
  try {
    await userStore.login(accountForm.username, accountForm.password)
    const redirect = (route.query.redirect as string) || '/'
    await router.replace(redirect)
    ElMessage.success('登录成功')
  } catch (error: unknown) {
    ElMessage.error(error instanceof Error ? error.message : '登录失败')
  } finally {
    loading.value = false
  }
}


function handleGetCode() {
  if (!phoneForm.phone) {
    ElMessage.warning('请输入手机号')
    return
  }
  if (isCountingDown.value) return

  isCountingDown.value = true
  countdown.value = 60

  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer!)
      isCountingDown.value = false
    }
  }, 1000)
}

function handleRegister() {
  emit('switch', 'register')
}

function handleForgot() {
  emit('switch', 'forgot')
}
</script>

<style lang="scss" scoped>
.login-page {
  width: 400px;
  display: flex;
  flex-direction: column;
  color: #fff;
}

.login-tabs {
  display: flex;
  margin-top: 30px;
  margin-bottom: 20px;

  .tab-item {
    padding: 10px 20px;
    cursor: pointer;
    color: #999;
    font-size: 16px;
    border-bottom: 2px solid transparent;
    transition: all 0.3s;

    &:hover {
      color: #666;
    }

    &.active {
      color: #fff;
      border-bottom-color: #8077FF;
    }
  }
}

.login-form {
  :deep(.el-input__wrapper) {
    background: rgba(255, 255, 255, 0.1);
    box-shadow: none;
    border: 1px solid transparent;
    border-radius: 8px;

    &.is-focus {
      border-color: #7c3aed;
    }
  }

  :deep(.el-input__inner) {
    color: #fff;

    &::placeholder {
      color: #999;
    }
  }

  :deep(.el-input__icon) {
    color: #999;
  }

  :deep(.el-input__password) {
    color: #fff;
  }

  :deep(.el-input-group__append) {
    background: #7c3aed;
    border: none;
    border-radius: 0 8px 8px 0;
    padding: 0;

    .el-button {
      color: #fff;
      border: none;
      background: transparent;
      padding: 0 15px;
      height: 100%;
      border-radius: 0 8px 8px 0;

      &:hover {
        background: #6d28d9;
      }
    }
  }

  .input-prefix {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #fff;
  }
}

.form-end {
  margin-top: 30px;
}

.form-links {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  font-size: 14px;

  .left-links {
    display: flex;
    align-items: center;
  }

  .link-text {
    color: #999;
  }

  .link-btn {
    color: #8077FF;
    cursor: pointer;

    &:hover {
      color: #9f95ff;
    }
  }
}

.login-code {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}
</style>
