import { AnimatePresence, motion } from 'framer-motion'
import { Button, Input } from '@heroui/react'
import React, { useState } from 'react'
import { variants } from './motionAnimate'
import { HistoryBarList } from './components/HistoryBarList'
import SearchIcon from '@/assets/svg/search.svg?react'
import HistoryMenuIcon from '@/assets/svg/historyMenu.svg?react'
import { ConversationModal } from '@/components/ConversationModal'
import { useAppSelector } from '@/store/hook'
import useToast from '@/hooks/useToast'
import CloseIcon from '@/assets/svg/close.svg?react'

interface HistoryBarProps {
  isVisible: boolean
  onSetHistoryVisible: (visible: boolean) => void
}

export const HistoryBar: React.FC<HistoryBarProps> = ({ isVisible, onSetHistoryVisible }) => {
  const showToast = useToast()
  const [isOpenConversationModal, setIsOpenConversationModal] = useState(false)
  const { conversations } = useAppSelector(state => state.conversation)
  const [searchValue, setSearchValue] = useState('')

  const handleOpen = () => {
    if (conversations.length === 0) {
      showToast('暂无记录，快去提问吧！', 'default', {
        icon: '🕑',
      })
      return
    }
    setIsOpenConversationModal(true)
  }
  return (
    <AnimatePresence>
      {isVisible && (
        <motion.div
          initial="hidden"
          animate="visible"
          exit="exit"
          variants={variants}
          className="fixed top-0 right-0 h-[100vh] w-[100vw] sm:relative sm:w-[252px] sm:rounded-[20px] sm:h-[80vh] sm:max-h-[800px] bg-[#F0FAFF] border-[1px] border-solid border-white ml-[12px]"
        >
          <div className="pt-[24px] flex flex-col h-full">
            <div className="flex gap-[12px] px-[32px] h-[40px] sm:block">
              <Input value={searchValue} onValueChange={setSearchValue} classNames={{ inputWrapper: ['bg-white', 'data-[hover=true]:bg-[#fff]', 'group-data-[focus=true]:bg-white', 'rounded-[24px]'] }} placeholder="搜索历史记录" startContent={<SearchIcon />} />
              <Button className="flex sm:hidden" onPress={() => onSetHistoryVisible(false)} isIconOnly color="danger">
                <CloseIcon />
              </Button>
            </div>
            <div className="px-[32px] flex-1 overflow-y-auto scrollbar-hide">
              <HistoryBarList onSetHistoryVisible={onSetHistoryVisible} searchValue={searchValue} />
            </div>
            <div className="text-[12px] border-t-solid border-t-[1px] border-t-[#82969C12] w-full h-[48px] flex items-center justify-center">
              <Button onPress={handleOpen} className="w-full" color="primary" variant="light" startContent={<HistoryMenuIcon />}>
                <span className="text-[#82969C]">管理对话记录</span>
              </Button>
            </div>
          </div>
          <ConversationModal isOpen={isOpenConversationModal} onClose={() => setIsOpenConversationModal(false)} />
        </motion.div>
      )}
    </AnimatePresence>
  )
}
