import React, { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { clearCurrentConversation, setCurrentConversation } from '@/store/conversationSlice'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { setIsAsking } from '@/store/chatSlice'
import type { RootState } from '@/store'

export function withRouteChangeHandler(WrappedComponent: React.ComponentType) {
  let beforeLocationPathName = ''
  return (props: any) => {
    const isAsking = useAppSelector((state: RootState) => state.chat.isAsking)
    const location = useLocation()
    const dispatch = useAppDispatch()
    const navigate = useNavigate()

    const newPath = location.pathname
    const oldPath = beforeLocationPathName

    useEffect(() => {
      if (isAsking && newPath !== oldPath && oldPath !== '') {
        dispatch(setIsAsking(false))
      }

      if (location.pathname === '/') {
        dispatch(clearCurrentConversation())
      }
      else if (location.pathname.startsWith('/chat/')) {
        const conversationId = location.pathname.split('/')[2]

        const tokenStr = window.localStorage.getItem('__TOKEN__') || '""'
        let token = ''
        try {
          token = JSON.parse(tokenStr)
        }
        catch {
          // 如果解析失败，说明没有有效的 token
          navigate('/')
          return // 提前返回，不执行后续的 dispatch
        }

        if (!token) {
          // 如果没有有效的 token，重定向到首页
          navigate('/')
          return // 提前返回，不执行后续的 dispatch
        }

        dispatch(setCurrentConversation(conversationId))
      }
      // 这里可以添加其他路由相关的逻辑
      beforeLocationPathName = newPath
    }, [location, dispatch])

    return <WrappedComponent {...props} />
  }
}
