import type React from 'react'
import { motion } from 'framer-motion'
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import styles from './Navbar.module.less'
import { NavBarItem } from './components/NavBarItem'
import { User } from './components/User'
import { clearNavigationFlag, createConversation } from '@/store/conversationSlice'
import type { WithAuthProps } from '@/auth/withAuth'
import { withAuth } from '@/auth/withAuth'
import { NAV_BAR_ITEMS } from '@/config/nav'
import { useAppDispatch, useAppSelector } from '@/store/hook'

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

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

  const { currentConversationId, shouldNavigateToNewConversation } = useAppSelector(state => state.conversation)

  const handleCreateConversation = () => {
    dispatch(createConversation({
      conversationData: {},
      shouldNavigate: true,
      shouldSendQuestion: '',
    }))
  }

  const handleClick = (type: string | undefined) => {
    if (!checkAuth())
      return

    if (type === 'add') {
      handleCreateConversation()
    }

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

    if (type === 'collect') {
      navigate('/collect')
    }

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

  useEffect(() => {
    if (shouldNavigateToNewConversation && currentConversationId) {
      navigate(`/chat/${currentConversationId}`)
      dispatch(clearNavigationFlag())
    }
  }, [shouldNavigateToNewConversation, currentConversationId, navigate, dispatch])

  return (
    <motion.nav className="h-full flex-shrink-0 flex flex-col items-center justify-center">
      <motion.div className={`${styles.layoutNavBarAgent} sm:flex hidden w-[64px] bg-white gap-[24px]`}>
        {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>
    </motion.nav>
  )
}

export const Navbar = withAuth(NavbarBase)
