import type React from 'react'
import { motion } from 'framer-motion'
import { useEffect, useRef, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useClickAway, useSessionStorageState } from 'ahooks'
import styles from './Navbar.module.less'
import { NavBarItem } from './components/NavBarItem'
import { clearNavigationFlag, createConversation } from '@/store/conversationSlice'
import { createTacticsConversation } from '@/store/tacticsSlice'
import type { WithAuthProps } from '@/auth/withAuth'
import { withAuth } from '@/auth/withAuth'
import { NAV_BAR_ITEMS } from '@/config/nav'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { isMobile } from '@/utils'
import { safeLocalStorageSetItem } from '@/lib/utils'
// import { User } from './components/User'

interface NavbarProps {
  isHistoryVisible: boolean
  onSetHistoryVisible: (visible: boolean) => void
}

const NavbarBase: React.FC<NavbarProps & WithAuthProps> = ({ isHistoryVisible, checkAuth, onSetHistoryVisible }) => {
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const location = useLocation()

  const { currentConversationId, shouldNavigateToNewConversation, currentToolId, shouldSendQuestion } = useAppSelector(state => state.conversation)
  const { currentConversationId: _tacticsConversationId, shouldNavigateToNewConversation: _tacticsShouldNavigate } = useAppSelector(state => state.tactics)

  const handleCreateConversation = () => {
    const sessionToolId = sessionStorage.getItem('currentToolId') || undefined
    dispatch(createConversation({
      conversationData: {
        ...(sessionToolId ? { toolId: sessionToolId } : {}),
      },
      shouldNavigate: true,
      shouldSendQuestion: '',
    }))
  }

  const handleCreateTacticsConversation = () => {
    dispatch(createTacticsConversation({
      conversationData: {},
      shouldNavigate: true,
      shouldSendQuestion: '',
    }))
  }

  const [isH5NavVisible, setIsH5NavVisible] = useState(isMobile())

  const handleClick = (type: string | undefined) => {
    if (type === 'logo') {
      if (!isH5NavVisible) {
        navigate('/')
        setIsH5NavVisible(true)
      }
      else {
        setIsH5NavVisible(!isH5NavVisible)
      }
      return
    }
    setIsH5NavVisible(true)
    if (!checkAuth()) {
      return
    }

    if (type === 'add') {
      // 判断是否为 tactics 聊天页面
      if (location.pathname.startsWith('/tactics/chat')) {
        handleCreateTacticsConversation()
      }
      else if (location.pathname.includes('/chat')) {
        handleCreateConversation()
      }
      else {
        navigate('/')
      }
      onSetHistoryVisible(false)
    }

    if (type === 'history') {
      onSetHistoryVisible(!isHistoryVisible)
    }

    if (type === 'collect') {
      // 从URL中提取会话ID并存储到 sessionStorage
      const pathParts = location.pathname.split('/')
      // 从路径中提取会话ID，获取 chat/ 后面的值
      // 查找 'chat' 在路径中的位置，然后获取其后一项作为会话ID
      const chatIndex = pathParts.indexOf('chat')
      const conversationId = chatIndex !== -1 && pathParts.length > chatIndex + 1
        ? pathParts[chatIndex + 1]
        : null

      if (conversationId) {
        sessionStorage.setItem('currentConversationId', conversationId)
      }
      navigate('/collect')
    }

    if (type === 'tools') {
      navigate('/tools')
    }
  }
  // const handleLogout = () => {
  //   onSetHistoryVisible(false)
  //   navigate('/')
  // }

  const [navBarVisibleLocal, setNavBarVisibleLocal] = useSessionStorageState<string | undefined>(
    '__NAV_BAR_VISIBLE_LOCAL__',
    {
      defaultValue: '0',
      listenStorageChange: true,
    },
  )

  const toggleNavBarVisible = () => {
    setNavBarVisibleLocal(navBarVisibleLocal === '1' ? '0' : '1')
  }

  useEffect(() => {
    if (shouldNavigateToNewConversation && currentConversationId) {
      // 如果当前有选中的 toolId，在 URL 中拼接，以便刷新页面后保留工具选择
      const url = currentToolId
        ? `/chat/${currentConversationId}?toolId=${currentToolId}`
        : `/chat/${currentConversationId}`
      // 通过 location.state 传递 toolId，避免在 Chat 页面被误判为"外链残留参数"而强制清空
      // 如果有 shouldSendQuestion，传递 skipHistoryLoad 标记，跳过历史记录加载
      navigate(url, {
        state: {
          toolId: currentToolId || null,
          skipHistoryLoad: Boolean(shouldSendQuestion),
        },
      })
      dispatch(clearNavigationFlag())
    }
  }, [shouldNavigateToNewConversation, currentConversationId, currentToolId, shouldSendQuestion, navigate, dispatch])

  // keep latest conversation id in localStorage (persists across page closes) and sessionStorage (for cross-page returns)
  useEffect(() => {
    if (currentConversationId) {
      // 保存到 localStorage，关闭页面后仍能恢复
      safeLocalStorageSetItem('currentConversationId', currentConversationId)
      // 同时保存到 sessionStorage，用于跨页面返回（如从收藏页返回）
      sessionStorage.setItem('currentConversationId', currentConversationId)
    }
  }, [currentConversationId])

  const navRef = useRef<HTMLButtonElement>(null)
  useClickAway(() => {
    setIsH5NavVisible(true)
  }, navRef)

  return (
    <>
      <motion.nav
        ref={navRef}
        animate={navBarVisibleLocal === '0' ? 'hidden' : ''}
        className="h-full flex-shrink-0 flex flex-col items-center justify-center relative"
      >
        {/* hidden */}
        <motion.div className={`layoutNavBarJoyride ${styles.layoutNavBarAgent}  rounded-full ${isH5NavVisible ? 'h-[55px] bg-white/70 shadow-md' : 'h-[380px]'} w-[54px] overflow-hidden py-[8px] sm:w-[64px] sm:bg-white gap-[24px] sm:h-auto sm:rounded-3xl sm:flex sm:py-[24px] sm:px-[8px]`}>
          {/* <NavBarItem isHistoryVisible={isHistoryVisible} onClick={handleClick} icon={Logo} label="" key="logo" type={isMobile() ? 'logo3' : 'logo'} /> */}

          {NAV_BAR_ITEMS.map((item) => {
            return (
              <NavBarItem isHistoryVisible={isHistoryVisible} onClick={handleClick} icon={item.icon} label={item.label} key={item.key} type={item.key} />
            )
          })}
          {/* <User onLogout={handleLogout} /> */}
        </motion.div>
        <div onClick={toggleNavBarVisible} className={`${styles.sidebarAction} ${navBarVisibleLocal === '0' ? styles.open : ''}`}></div>
      </motion.nav>
      {/* <JoyrideStep /> */}
    </>
  )
}

export const Navbar = withAuth(NavbarBase)
