import { Badge } from '@/components/ui/badge'
import { useCurrentUser, useUserNoticeStat } from '@/hooks/auth'
import Image from 'next/image'
import { useState, useEffect } from 'react'
import { usePathname } from 'next/navigation'
import { useQueryClient } from '@tanstack/react-query'
import { userKeys } from '@/lib/query-keys'
import NoticeDrawer from './NoticeDrawer'

const Notice = ({ actualIsExpanded }: { actualIsExpanded: boolean }) => {
  const { data: user } = useCurrentUser()
  const [isDrawerOpen, setIsDrawerOpen] = useState(false)
  const pathname = usePathname()
  const queryClient = useQueryClient()

  const { data } = useUserNoticeStat()

  // 监听路径变化，刷新通知统计
  useEffect(() => {
    if (user) {
      // 当路径变化时，无效化并重新获取通知统计数据
      queryClient.invalidateQueries({
        queryKey: userKeys.noticeStat(),
      })
    }
  }, [pathname])

  useEffect(() => {
    if (isDrawerOpen && user) {
      queryClient.invalidateQueries({
        queryKey: userKeys.noticeStat(),
      })
    }
  }, [isDrawerOpen])

  return (
    <div>
      {/* 分割线 */}
      {user && (
        <div className="mx-6 my-4">
          <div className="bg-outline-normal h-px" />
        </div>
      )}

      {/* 底部通知 */}
      {user && (
        <div className="px-4">
          <div
            className="hover:bg-surface-element-hover flex cursor-pointer items-center gap-3 rounded-full p-2 transition-colors"
            onClick={() => setIsDrawerOpen(true)}
          >
            <div className="relative flex h-8 w-8 flex-shrink-0 items-center justify-center">
              <Image src="/icons/notice.svg" alt="Notice" width={32} height={32} />
              <Badge count={data?.unRead} className="absolute -top-2 -right-2" />
            </div>
            {actualIsExpanded && (
              <span className="txt-label-m text-txt-primary-normal flex-1">Notice</span>
            )}
          </div>
        </div>
      )}

      {/* 通知抽屉 */}
      <NoticeDrawer isOpen={isDrawerOpen} onOpenChange={setIsDrawerOpen} />
    </div>
  )
}

export default Notice
