// AuthContext.tsx
import type { ReactNode } from 'react'
import React, { createContext, useContext, useEffect, useState } from 'react'
import { useLocalStorageState } from 'ahooks'
import { fetchLoginByUid } from '@/api/common'
import useToast from '@/hooks/useToast'

interface AuthContextType {
  isLoggedIn: boolean
  showLoginModal: boolean
  showLoginTip: boolean
  login: () => void
  logout: () => void
  toggleLoginModal: () => void
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

interface AuthProviderProps {
  children: ReactNode
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const showToast = useToast()
  const [token, setToken] = useLocalStorageState<string | undefined>(
    '__TOKEN__',
    {
      defaultValue: '',
    },
  )

  const [isLoggedIn, setIsLoggedIn] = useState(!!token)
  const [showLoginModal, setShowLoginModal] = useState(false)
  const [showLoginTip, setShowLoginTip] = useState(!token)

  const login = async () => {
    const res = await fetchLoginByUid('123123')
    if (res.data) {
      setToken(res.data.token)
      setIsLoggedIn(true)
      setShowLoginModal(false)
      showToast('欢迎使用晓得AI助手～', 'success', { icon: '🎉' })
      return
    }
    showToast('登录失败', 'error')
  }

  const logout = () => {
    setIsLoggedIn(false)
    setToken('')
    showToast('期待您再次使用~', 'success', { icon: '👋🏻' })
  }

  const toggleLoginModal = () => {
    setShowLoginModal(!showLoginModal)
    setShowLoginTip(showLoginModal)
  }

  // 监听 localStorage 变化事件
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === '__TOKEN__') {
        const newToken = e.newValue
        setIsLoggedIn(!!newToken)
        if (!newToken) {
          setShowLoginTip(true)
        }
      }
    }

    window.addEventListener('storage', handleStorageChange)
    return () => {
      window.removeEventListener('storage', handleStorageChange)
    }
  }, [])

  // 添加 effect 监听 token 变化
  useEffect(() => {
    setIsLoggedIn(!!token)
    if (!token) {
      setShowLoginTip(true)
    }
  }, [token])

  return (
    // eslint-disable-next-line react/no-unstable-context-value
    <AuthContext.Provider value={{ isLoggedIn, showLoginTip, showLoginModal, login, logout, toggleLoginModal }}>
      {children}
    </AuthContext.Provider>
  )
}

// eslint-disable-next-line react-refresh/only-export-components
export function useAuth(): AuthContextType {
  const context = useContext(AuthContext)
  if (context === null) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}
