<template>
  <div class="admin--login">
    <div class="login--container">
      <div class="login--box">
        <div class="login--logo">
          <h1>AUDI</h1>
          <p class="subtitle">Admin Panel</p>
        </div>
        
        <form @submit.prevent="handleLogin" class="login--form">
          <div v-if="errorMessage" class="login--error">
            {{ errorMessage }}
          </div>

          <div class="form--group">
            <input
              v-model="username"
              type="text"
              placeholder="아이디"
              class="form--input"
              required
              :disabled="isLoading"
            >
          </div>

          <div class="form--group">
            <input
              v-model="password"
              type="password"
              placeholder="비밀번호"
              class="form--input"
              required
              :disabled="isLoading"
            >
          </div>

          <div class="form--options">
            <label class="checkbox--label">
              <input type="checkbox" v-model="rememberMe" :disabled="isLoading">
              <span>로그인 상태 유지</span>
            </label>
            <a href="#" class="forgot--password">비밀번호 찾기</a>
          </div>

          <button type="submit" class="login--button" :disabled="isLoading">
            {{ isLoading ? '로그인 중...' : '로그인' }}
          </button>
        </form>
        
        <div class="login--footer">
          <p>© 2024 Audi. All rights reserved.</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

definePageMeta({
  layout: false,
  middleware: ['auth']
})

const { post } = useApi()

const username = ref('')
const password = ref('')
const rememberMe = ref(false)
const isLoading = ref(false)
const errorMessage = ref('')

const handleLogin = async () => {
  if (!username.value || !password.value) {
    errorMessage.value = '아이디와 비밀번호를 입력해주세요.'
    return
  }

  isLoading.value = true
  errorMessage.value = ''

  try {
    const { data, error } = await post('/auth/login', {
      username: username.value,
      password: password.value,
      remember: rememberMe.value
    })

    if (error) {
      errorMessage.value = error.message || '로그인에 실패했습니다.'
      return
    }

    // API 응답: { success: true, data: { token, admin }, message }
    if (data?.success && data?.data?.token) {
      console.log('[Login] 로그인 성공, 토큰 저장:', data.data.token.substring(0, 20) + '...')

      localStorage.setItem('admin_token', data.data.token)

      if (data.data.admin) {
        localStorage.setItem('admin_user', JSON.stringify(data.data.admin))
      }

      console.log('[Login] localStorage 확인:', localStorage.getItem('admin_token') ? '저장됨' : '저장 실패')

      // 로그인 성공 후 dashboard로 이동
      await navigateTo('/admin/dashboard')
    } else {
      errorMessage.value = data?.message || '로그인 정보가 올바르지 않습니다.'
    }
  } catch (error) {
    errorMessage.value = '서버 오류가 발생했습니다.'
    console.error('Login error:', error)
  } finally {
    isLoading.value = false
  }
}
</script>