import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from './useToast'
import { auth } from '../utils/api'
import { authUtils } from '../utils/auth'

// 清理可能存在的无效数据
try {
  const encryptedUser = localStorage.getItem('user')
  if (encryptedUser === 'undefined' || encryptedUser === undefined) {
    localStorage.removeItem('user')
  }
} catch (e) {
  localStorage.removeItem('user')
}

const getUserFromStorage = () => {
  try {
    const encryptedUser = localStorage.getItem('user')
    return encryptedUser ? authUtils.decrypt(encryptedUser) : null
  } catch (e) {
    console.error('Failed to decrypt user data from localStorage:', e)
    return null
  }
}

const getTokenFromStorage = () => {
  try {
    const encryptedToken = localStorage.getItem('token')
    return encryptedToken ? authUtils.decrypt(encryptedToken) : null
  } catch (e) {
    console.error('Failed to decrypt token from localStorage:', e)
    return null
  }
}

const user = ref(getUserFromStorage())
const token = ref(getTokenFromStorage())

export function useAuth() {
  const router = useRouter()
  const { showToast } = useToast()

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

  const setAuth = ({ user: userData, token: accessToken, refresh_token }) => {
    user.value = userData
    token.value = accessToken
    localStorage.setItem('user', authUtils.encrypt(userData))
    localStorage.setItem('token', authUtils.encrypt(accessToken))
    if (refresh_token) {
      localStorage.setItem('refreshToken', authUtils.encrypt(refresh_token))
    }
  }

  const clearAuth = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    authUtils.broadcastAuthChange('logout')
  }

  const login = async (email, password) => {
    try {
      const { data } = await auth.login({ email, password })
      if (data) {
        setAuth({
          user: data.user,
          token: data.access_token,
          refresh_token: data.refresh_token
        })
        showToast('登录成功', 'success')
        router.push('/')
        return true
      }
      return false
    } catch (error) {
      console.error('Login error:', error)
      showToast(error.message || '登录失败', 'error')
      return false
    }
  }

  const register = async (userData) => {
    try {
      const { data } = await auth.register(userData)
      if (data) {
        showToast('注册成功，请登录', 'success')
        router.push('/login')
        return true
      }
      return false
    } catch (error) {
      console.error('Register error:', error)
      showToast(error.message || '注册失败', 'error')
      return false
    }
  }

  const logout = () => {
    clearAuth()
    router.push('/login')
  }

  return {
    user,
    token,
    isAuthenticated,
    login,
    logout,
    register,
    setAuth,
    clearAuth
  }
}
