// AuthContext.tsx
import type { ReactNode } from 'react'
import React, { createContext, useContext, 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('123')
    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)
  }

  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 === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}
