'use client'

import { useAtomValue } from 'jotai'
import { imReconnectStatusAtom, IMReconnectStatus } from '@/atoms/im'
import { cn } from '@/lib/utils'
import { useEffect, useState } from 'react'

interface IMReconnectStatusProps {
  className?: string
}

const IMReconnectStatusBar: React.FC<IMReconnectStatusProps> = ({ className }) => {
  const reconnectStatus = useAtomValue(imReconnectStatusAtom)
  const [isVisible, setIsVisible] = useState(false)

  // 控制状态条的显示/隐藏
  useEffect(() => {
    if (reconnectStatus === IMReconnectStatus.CONNECTED) {
      // 连接成功后，延迟隐藏状态条
      const timer = setTimeout(() => {
        setIsVisible(false)
      }, 2000)
      return () => clearTimeout(timer)
    } else if (reconnectStatus !== IMReconnectStatus.DISCONNECTED) {
      // 断线、重连中、失败时立即显示
      setIsVisible(true)
    }
  }, [reconnectStatus])

  // 不显示时返回null
  if (!isVisible) {
    return null
  }

  const getStatusConfig = () => {
    switch (reconnectStatus) {
      case IMReconnectStatus.DISCONNECTED:
        return {
          text: '连接已断开',
          bgColor: 'bg-error-default',
          textColor: 'text-white',
          icon: 'icon-status-error',
        }
      case IMReconnectStatus.RECONNECTING:
        return {
          text: '正在重连...',
          bgColor: 'bg-warning-default',
          textColor: 'text-white',
          icon: 'icon-loading',
          animate: true,
        }
      case IMReconnectStatus.FAILED:
        return {
          text: '重连失败，请刷新页面',
          bgColor: 'bg-error-default',
          textColor: 'text-white',
          icon: 'icon-status-error',
        }
      case IMReconnectStatus.CONNECTED:
        return {
          text: '连接已恢复',
          bgColor: 'bg-success-default',
          textColor: 'text-white',
          icon: 'icon-check',
        }
      default:
        return null
    }
  }

  const statusConfig = getStatusConfig()

  if (!statusConfig) return null

  return (
    <div
      className={cn(
        'fixed top-0 right-0 left-0 z-50 flex items-center justify-center px-4 py-2 text-sm font-medium transition-all duration-300 ease-in-out',
        'bg-positive-normal',
        // statusConfig.bgColor,
        // statusConfig.textColor,
        className
      )}
    >
      <div className="flex items-center gap-2">
        <i
          className={cn(
            'iconfont text-base',
            statusConfig.icon,
            statusConfig.animate && 'animate-spin'
          )}
        />
        <span>{statusConfig.text}</span>
      </div>
    </div>
  )
}

export default IMReconnectStatusBar
