import type React from 'react'
import { motion } from 'framer-motion'
import { useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { useSessionStorageState } from 'ahooks'
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 MingcuteArrowsRightFill from '@/assets/svg/MingcuteArrowsRightFill.svg?react'
import { isMobile } from '@/utils'
import { useAppDispatch } from '@/store/hook'
import { fetchConversations } from '@/store/conversationSlice'

interface MainLayoutProps {
  children: React.ReactNode
}

const contentVariants = {
  navTween: {
    x: '-90px', // 向左移出屏幕
    transition: { type: 'tween', duration: 0.3, ease: 'easeInOut' },
  },
  mainTween: {
    x: '-60px', // 向左移出屏幕
    transition: { type: 'tween', duration: 0.3, ease: 'easeInOut' },
  },
  expanded: {
    width: '90px',
    x: 0, // 恢复原位
    transition: { type: 'spring', stiffness: 300, damping: 30 },
  },
  shrunk: {
    width: isMobile() ? '90px' : '340px',
    x: 0, // 恢复原位
    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 [navBarVisibleLocal] = useSessionStorageState<string | undefined>(
    '__NAV_BAR_VISIBLE_LOCAL__',
    {
      defaultValue: '0',
      listenStorageChange: true,
    },
  )

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

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

  // 判断是否为问答功能页面
  const isTacticsPage = location.pathname.startsWith('/tactics')

  return (
    <motion.main className={styles.layoutMain}>
      {/* 问答功能页面不显示导航栏和历史记录 */}
      {!isTacticsPage && (
        <motion.div
          animate={navBarVisibleLocal === '0' ? isHistoryVisible ? 'shrunk' : 'expanded' : 'navTween'}
          variants={contentVariants}
          className={`fixed right-[-12px] top-[10px] z-[49] h-auto sm:relative flex sm:h-full 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
        variants={contentVariants}
        animate={navBarVisibleLocal === '0' || isTacticsPage ? '' : 'mainTween'}
        className={`${styles.layoutContent} ${isTacticsPage ? 'px-0' : 'px-[12px]'}`}
      >
        {children}
      </motion.div>

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