import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('admin_token') || '')
  const refreshToken = ref(localStorage.getItem('admin_refresh_token') || '')
  const admin = ref(JSON.parse(localStorage.getItem('admin_info') || 'null'))
  const tokenExpiry = ref(parseInt(localStorage.getItem('admin_token_expiry') || '0'))
  
  let refreshTimer = null

  const isAuthenticated = computed(() => !!token.value)

  // Check if token is about to expire (within 5 minutes)
  function isTokenExpiringSoon() {
    if (!tokenExpiry.value) return false
    const now = Date.now()
    const fiveMinutes = 5 * 60 * 1000
    return tokenExpiry.value - now < fiveMinutes
  }

  // Parse JWT to get expiry time
  function parseTokenExpiry(jwtToken) {
    try {
      const payload = JSON.parse(atob(jwtToken.split('.')[1]))
      return payload.exp * 1000 // Convert to milliseconds
    } catch {
      return 0
    }
  }

  // Schedule token refresh
  function scheduleTokenRefresh() {
    if (refreshTimer) {
      clearTimeout(refreshTimer)
    }
    
    if (!token.value || !tokenExpiry.value) return
    
    const now = Date.now()
    const refreshTime = tokenExpiry.value - now - (5 * 60 * 1000) // Refresh 5 minutes before expiry
    
    if (refreshTime > 0) {
      refreshTimer = setTimeout(async () => {
        await attemptTokenRefresh()
      }, refreshTime)
    } else if (isTokenExpiringSoon()) {
      // Token is already expiring soon, refresh immediately
      attemptTokenRefresh()
    }
  }

  // Attempt to refresh the token
  async function attemptTokenRefresh() {
    if (!refreshToken.value) {
      logout()
      return false
    }
    
    try {
      const response = await api.post('/api/v1/admin/refresh-token', {
        refreshToken: refreshToken.value
      })
      
      if (response.data.success) {
        setTokenData(response.data.data.token, response.data.data.refreshToken)
        return true
      }
    } catch (error) {
      console.error('Token refresh failed:', error)
    }
    
    logout()
    return false
  }

  // Set token data and schedule refresh
  function setTokenData(newToken, newRefreshToken = null) {
    token.value = newToken
    tokenExpiry.value = parseTokenExpiry(newToken)
    localStorage.setItem('admin_token', newToken)
    localStorage.setItem('admin_token_expiry', tokenExpiry.value.toString())
    
    if (newRefreshToken) {
      refreshToken.value = newRefreshToken
      localStorage.setItem('admin_refresh_token', newRefreshToken)
    }
    
    scheduleTokenRefresh()
  }

  async function login(username, password) {
    const response = await api.post('/api/v1/admin/login', { username, password })
    // 后端返回 code: 0 表示成功，转换为 success: true 格式
    const isSuccess = response.data.success || response.data.code === 0
    if (isSuccess) {
      const { token: newToken, refreshToken: newRefreshToken, admin: adminData } = response.data.data
      
      setTokenData(newToken, newRefreshToken)
      admin.value = adminData
      localStorage.setItem('admin_info', JSON.stringify(adminData))
    }
    return { ...response.data, success: isSuccess }
  }

  function logout() {
    if (refreshTimer) {
      clearTimeout(refreshTimer)
      refreshTimer = null
    }
    
    token.value = ''
    refreshToken.value = ''
    admin.value = null
    tokenExpiry.value = 0
    
    localStorage.removeItem('admin_token')
    localStorage.removeItem('admin_refresh_token')
    localStorage.removeItem('admin_info')
    localStorage.removeItem('admin_token_expiry')
  }

  function setToken(newToken) {
    setTokenData(newToken)
  }

  // Initialize token refresh on store creation
  function initializeAuth() {
    if (token.value && tokenExpiry.value) {
      const now = Date.now()
      if (tokenExpiry.value <= now) {
        // Token already expired, try to refresh
        attemptTokenRefresh()
      } else {
        scheduleTokenRefresh()
      }
    }
  }

  // Call initialize on store creation
  initializeAuth()

  return {
    token,
    refreshToken,
    admin,
    isAuthenticated,
    isTokenExpiringSoon,
    login,
    logout,
    setToken,
    attemptTokenRefresh,
    initializeAuth
  }
})
