import { storeToRefs } from 'pinia'

import { useAdminLoginMutation } from '@/services/api/monisuo-admin.api'
import { useAuthStore } from '@/stores/auth'

export function useAuth() {
  const router = useRouter()

  const authStore = useAuthStore()
  const { isLogin, adminInfo } = storeToRefs(authStore)
  const loading = ref(false)
  const error = ref<string | null>(null)

  const loginMutation = useAdminLoginMutation()

  function logout() {
    authStore.logout()
    router.push({ path: '/auth/sign-in' })
  }

  function toHome() {
    router.push({ path: '/monisuo/dashboard' })
  }

  async function login(username: string, password: string) {
    loading.value = true
    error.value = null

    try {
      const result = await loginMutation.mutateAsync({ username, password })
      console.log('Login result:', result)

      if (result.code === '0000' && result.data) {
        console.log('Setting token and adminInfo...')
        authStore.setToken(result.data.token)
        authStore.setAdminInfo(result.data.adminInfo)
        console.log('isLogin after setToken:', authStore.isLogin)

        const redirect = router.currentRoute.value.query.redirect as string
        console.log('Redirecting to:', redirect || '/monisuo/dashboard')
        if (!redirect || redirect.startsWith('//')) {
          toHome()
        }
        else {
          router.push(redirect)
        }
      }
      else {
        console.log('Login failed:', result.code, result.msg)
        error.value = result.msg || '登录失败'
      }
    }
    catch (e: any) {
      console.error('Login error:', e)
      error.value = e.response?.data?.msg || '网络错误，请稍后重试'
    }
    finally {
      loading.value = false
    }
  }

  return {
    loading,
    error,
    isLogin,
    adminInfo,
    logout,
    login,
  }
}
