<script setup lang="ts">
import Brand from '@/components/Brand.vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { api } from '@/utils/request'
import { ApiError } from '@/types/api'
import type { UserInfo } from '@/stores/user'

const formState = reactive({
  username: '',
  password: '',
  remember: true,
})

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

const formRef = ref()
const loading = ref(false)
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const data = await api.post<{
      access_token: string
      refresh_token: string
      user: UserInfo
    }>('/api/v1/login', {
      username: formState.username,
      password: formState.password,
    })

    userStore.setToken(data.access_token, data.refresh_token, formState.remember)
    userStore.setUser(data.user)

    message.success('登录成功！')
    // 校验 redirect 防止开放重定向漏洞
    const redirect = (route.query.redirect as string) || '/'
    const safeRedirect = redirect.startsWith('/') && !redirect.includes('//') ? redirect : '/'
    setTimeout(() => {
      router.push(safeRedirect)
    }, 500)
  } catch (error: unknown) {
    if (error && typeof error === 'object' && 'errorFields' in error) {
      return
    }
    if (error instanceof ApiError) {
      message.error(error.message)
      return
    }
    console.error('登录错误：', error)
    message.error('登录失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="flex flex-col lg:flex-row min-h-screen">
    <!-- 左侧图片区域 -->
    <div class="w-full lg:w-1/2 relative overflow-hidden bg-linear-to-br from-[#4da30d] to-[#377508] min-h-[200px] lg:min-h-screen">
      <img
        src="@/assets/images/bg.jpeg"
        alt="Background"
        class="absolute inset-0 w-full h-full object-cover"
      />
      <div class="absolute inset-0 bg-black/20"></div>
    </div>

    <!-- 右侧表单区域 -->
    <div class="w-full lg:w-1/2 flex items-center bg-white p-6 md:p-8 lg:pl-12 lg:pr-12">
      <div class="w-full max-w-md">
        <!-- Brand Logo -->
        <div class="mb-8">
          <Brand size="large" show-app-name />
        </div>

        <!-- 表单标题 -->
        <div class="mb-8">
          <h1 class="text-3xl font-bold text-gray-800 mb-2">用户登录</h1>
          <p class="text-gray-600">欢迎回到 DataHub</p>
        </div>

        <!-- 登录表单 -->
        <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          layout="vertical"
          @finish="handleSubmit"
        >
          <a-form-item label="用户名" name="username">
            <a-input
              v-model:value="formState.username"
              size="large"
              placeholder="请输入用户名"
            >
              <template #prefix>
                <UserOutlined class="text-gray-400" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="密码" name="password">
            <a-input-password
              v-model:value="formState.password"
              size="large"
              placeholder="请输入密码"
            >
              <template #prefix>
                <LockOutlined class="text-gray-400" />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item>
            <div class="flex justify-between items-center">
              <a-checkbox v-model:checked="formState.remember">
                记住我
              </a-checkbox>
              <a-button type="link" class="p-0 h-auto text-[#4da30d] hover:text-[#5fc910]">
                忘记密码？
              </a-button>
            </div>
          </a-form-item>

          <a-form-item class="mt-6">
            <a-button
              type="primary"
              html-type="submit"
              size="large"
              :loading="loading"
              block
              class="h-12 text-base font-medium bg-[#4da30d] hover:bg-[#5fc910] border-none"
            >
              登录
            </a-button>
          </a-form-item>

          <div class="text-center mt-4">
            <span class="text-gray-600 text-sm">还没有账户？</span>
            <a-button type="link" class="text-[#4da30d] hover:text-[#5fc910]" @click="goToRegister">
              立即注册
            </a-button>
          </div>
        </a-form>
      </div>
    </div>
  </div>
</template>
