import type React from 'react'
import { motion } from 'framer-motion'
import { useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { Navbar } from '../Navbar'
import { HistoryBar } from '../HistoryBar/HistoryBar'
import styles from './MainLayout.module.less'
import { useAuth } from '@/auth/AuthContext'
import { LoginModal } from '@/components/LoginModal'
import { useAppDispatch } from '@/store/hook'
import { fetchConversations } from '@/store/conversationSlice'
import MingcuteArrowsRightFill from '@/assets/svg/MingcuteArrowsRightFill.svg?react'
import { isMobile } from '@/utils'

interface MainLayoutProps {
  children: React.ReactNode
}

const contentVariants = {
  expanded: {
    width: '90px',
    transition: { type: 'spring', stiffness: 300, damping: 30 },
  },
  shrunk: {
    width: isMobile() ? '90px' : '340px',
    transition: { type: 'spring', stiffness: 300, damping: 30 },
  },
}

export const MainLayout: React.FC<MainLayoutProps> = ({ children }) => {
  const { showLoginModal, toggleLoginModal } = useAuth()
  const [isHistoryVisible, setHistoryVisible] = useState(false)
  const location = useLocation()
  const dispatch = useAppDispatch()
  const token = window.localStorage.getItem('__TOKEN__')

  useEffect(() => {
    if (token) {
      dispatch(fetchConversations())
    }
  }, [dispatch])

  useEffect(() => {
    if (location.pathname === '/tools' || location.pathname === '/collect') {
      setHistoryVisible(false)
    }
  }, [location.pathname])

  return (
    <motion.main className={styles.layoutMain}>
      {/* hidden */}
      <motion.div
        animate={isHistoryVisible ? 'shrunk' : 'expanded'}
        variants={contentVariants}
        className={`fixed right-[0] top-[22px] z-[49] h-auto sm:relative flex sm:h-full pl-[12px] items-center ${isHistoryVisible && !isMobile() ? 'w-[340px]' : 'w-[90px]'} box-border`}
      >
        <Navbar isHistoryVisible={isHistoryVisible} onSetHistoryVisible={setHistoryVisible} />
        <HistoryBar isVisible={isHistoryVisible} onSetHistoryVisible={setHistoryVisible} />
        {!isHistoryVisible && (
          <motion.div
            initial="hidden"
            animate="visible"
            variants={{
              hidden: {
                x: -5,
                opacity: 0,
              },
            }}
            className={`${styles.sidebarArrow} side-bar-arrow h-[42px] flex items-center`}
          >
            <MingcuteArrowsRightFill className="text-[#818d91]" />
          </motion.div>
        )}
      </motion.div>
      <motion.div
        className={`${styles.layoutContent}`}
      >
        {children}
      </motion.div>

      <LoginModal isOpen={showLoginModal} onClose={toggleLoginModal} />
    </motion.main>
  )
}
