import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useChatConfig } from "../../context/chatConfig";
import { useCurrentUser } from "@/hooks/auth";
import { HeartbeatLevel } from "@/services/im";
import { cn } from "@/lib/utils";
import { Tag } from "@/components/ui/tag";
import { useState, useEffect, useRef } from "react";
import Image from "next/image";
import AIRelationTag from "@/components/features/AIRelationTag";
import Link from "next/link";
import { useSetAtom } from "jotai";
import { createDrawerOpenState, isCrushLevelDrawerOpenAtom } from "@/atoms/chat";

interface CrushLevelAvatarProps {
  size?: "large" | "small";
  showAnimation?: boolean;
  noLink?: boolean;
  showText?: boolean;
  hideIcon?: boolean;
}

const CrushLevelAvatar = ({
  size = "small",
  showAnimation = false,
  noLink = false,
  showText = false,
  hideIcon = false
}: CrushLevelAvatarProps) => {
  const { aiInfo, aiId } = useChatConfig();
  const { data: currentUser } = useCurrentUser();
  
  const { headImg, nickname, aiUserHeartbeatRelation } = aiInfo || {};
  const { headImage: currentUserHeadImg } = currentUser || {};
  const { heartbeatLevel, heartbeatVal, heartbeatLevelName, title, isShow } = aiUserHeartbeatRelation || {};
  
  const [animationKey, setAnimationKey] = useState(0);
  const [isLevelChanging, setIsLevelChanging] = useState(false);
  const [displayLevel, setDisplayLevel] = useState(heartbeatLevel);
  const [showNumber, setShowNumber] = useState(true);
  const [isFirstLoad, setIsFirstLoad] = useState(true); // 标记是否为第一次加载
  const [currentAiId, setCurrentAiId] = useState(aiId); // 追踪当前的 aiId
  const [unlockNotification, setUnlockNotification] = useState<{
    show: boolean;
    isUpgrade: boolean;
    title: string;
    animationState: 'slide-in-up' | 'showing' | 'fade-in' | 'slide-out-down' | 'hidden';
  }>({
    show: false,
    isUpgrade: true,
    title: '',
    animationState: 'hidden'
  });

  const setIsCrushLevelDrawerOpen = useSetAtom(isCrushLevelDrawerOpenAtom);
  
  // 用于管理解锁权益浮窗定时器的引用
  const unlockNotificationTimersRef = useRef<{
    showTimer?: NodeJS.Timeout;
    hideTimer?: NodeJS.Timeout;
  }>({});

  // 清除解锁权益浮窗的所有定时器并重置状态
  const clearUnlockNotificationTimers = () => {
    if (unlockNotificationTimersRef.current.showTimer) {
      clearTimeout(unlockNotificationTimersRef.current.showTimer);
      unlockNotificationTimersRef.current.showTimer = undefined;
    }
    if (unlockNotificationTimersRef.current.hideTimer) {
      clearTimeout(unlockNotificationTimersRef.current.hideTimer);
      unlockNotificationTimersRef.current.hideTimer = undefined;
    }
    setUnlockNotification({
      show: false,
      isUpgrade: true,
      title: '',
      animationState: 'hidden'
    });
  };

  // 监听 AI 切换，重置相关状态
  useEffect(() => {
    if (aiId !== currentAiId) {
      // AI 切换时，清除所有定时器和状态
      clearUnlockNotificationTimers();
      setIsLevelChanging(false);
      setShowNumber(true);
      setIsFirstLoad(true);
      setDisplayLevel(heartbeatLevel);
      setCurrentAiId(aiId);
    }
  }, [aiId, currentAiId, heartbeatLevel]);

  // 监听等级变化事件触发动画
  useEffect(() => {
    const handleLevelChange = (event: CustomEvent) => {
      const { type, aiId: eventAiId, newLevel, title: eventTitle } = event.detail;
      console.log('handleLevelChange 11', eventAiId === `${aiId}`, eventAiId, aiId)
      
      // 只处理当前AI的等级变化事件且需要显示动画
      if (`${eventAiId}` === `${aiId}` && showAnimation) {
        // 清除之前的解锁权益浮窗状态和定时器
        clearUnlockNotificationTimers();
        
        setIsLevelChanging(true);
        setAnimationKey(prev => prev + 1);
        setShowNumber(false); // 隐藏数字
        
        // 判断是升级还是降级
        const isUpgrade = type === 'up';
        const newLevelNumber = newLevel?.replace('LEVEL_', '') || '1';
        
        // 心形缩放完成后显示新数字
        setTimeout(() => {
          setDisplayLevel(newLevel);
          setShowNumber(true);
        }, 400); // 心形缩放动画时长
        
        // 显示解锁权益浮窗
        unlockNotificationTimersRef.current.showTimer = setTimeout(() => {
          setUnlockNotification({
            show: true,
            isUpgrade,
            title: eventTitle || (isUpgrade ? `Unlocked "Level ${newLevelNumber}" title` : `Lost "Level ${displayLevel?.replace('LEVEL_', '') || '1'}" privilege`),
            animationState: isUpgrade ? 'slide-in-up' : 'fade-in' // 升级从下往上滑入，降级直接淡入
          });
        }, 800); // 等心形动画完成后再显示
        
        // 背景消失后重置状态
        setTimeout(() => {
          setIsLevelChanging(false);
        }, 2000); // 背景消失动画时长
      }
    };

    // 添加事件监听器
    window.addEventListener('heartbeat-level-change-top', handleLevelChange as EventListener);

    return () => {
      // 清理事件监听器
      window.removeEventListener('heartbeat-level-change-top', handleLevelChange as EventListener);
    };
  }, [aiId, showAnimation, displayLevel, clearUnlockNotificationTimers]);

  // 初始化显示等级
  useEffect(() => {
    if (!displayLevel) {
      setDisplayLevel(heartbeatLevel);
      setIsFirstLoad(false); // 第一次设置等级后，标记为非首次加载
    } else if (isFirstLoad && displayLevel) {
      setIsFirstLoad(false); // 如果已有等级，直接标记为非首次加载
    }
  }, [heartbeatLevel, displayLevel, isFirstLoad]);

  // 处理解锁权益浮窗的动画状态
  useEffect(() => {
    if (unlockNotification.show && (unlockNotification.animationState === 'slide-in-up' || unlockNotification.animationState === 'fade-in')) {
      // 清除之前的hideTimer（如果有的话）
      if (unlockNotificationTimersRef.current.hideTimer) {
        clearTimeout(unlockNotificationTimersRef.current.hideTimer);
      }
      
      // 滑入/淡入完成后，保持显示3秒
      unlockNotificationTimersRef.current.hideTimer = setTimeout(() => {
        setUnlockNotification(prev => ({
          ...prev,
          animationState: prev.isUpgrade ? 'showing' : 'slide-out-down' // 升级保持显示，降级从上到下消失
        }));
      }, 3000);
    } else if (unlockNotification.animationState === 'showing') {
      // 升级浮窗显示3秒后淡出
      const timer = setTimeout(() => {
        setUnlockNotification({
          show: false,
          isUpgrade: true,
          title: '',
          animationState: 'hidden'
        });
        // 清除定时器引用
        unlockNotificationTimersRef.current.hideTimer = undefined;
      }, 300); // 淡出动画时长

      return () => clearTimeout(timer);
    } else if (unlockNotification.animationState === 'slide-out-down') {
      // 降级浮窗从上到下滑出后隐藏
      const timer = setTimeout(() => {
        setUnlockNotification({
          show: false,
          isUpgrade: true,
          title: '',
          animationState: 'hidden'
        });
        // 清除定时器引用
        unlockNotificationTimersRef.current.hideTimer = undefined;
      }, 500); // 滑出动画时长

      return () => clearTimeout(timer);
    }
  }, [unlockNotification.show, unlockNotification.animationState]);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      clearUnlockNotificationTimers();
    };
  }, []);

  const handleRelationTagClick = () => {
    if (noLink) return;
    setIsCrushLevelDrawerOpen(createDrawerOpenState(true));
  }

  // 如果没有等级，只显示AI头像
  if (!heartbeatLevel) {
    return (
      <div className="flex flex-col items-center gap-6">
        {!noLink ? (
          <Link href={`/@${aiId}`}>
            <Avatar className={cn("size-20", size === "large" ? "size-20" : "size-20")}>
              <AvatarImage className="object-cover" src={headImg} />
              <AvatarFallback>
                {nickname?.slice(0, 1)}
              </AvatarFallback>
            </Avatar>
          </Link>
        ) : (
          <Avatar className={cn("size-20", size === "large" ? "size-20" : "size-20")}>
            <AvatarImage className="object-cover" src={headImg} />
            <AvatarFallback>
              {nickname?.slice(0, 1)}
            </AvatarFallback>
          </Avatar>
        )}
        <div className="txt-headline-s text-center">{nickname}</div>
      </div>
    );
  }

  return (
    <div className="flex flex-col items-center gap-6 relative">
      <div className="relative">
        {/* 头像组合 */}
        <div className="flex items-center justify-center gap-4 relative">
           {/* 动画双心：在头像底部，升级/降级时触发 */}
           {isLevelChanging && showAnimation && (
            <div className="absolute left-1/2 bottom-[-70px] -translate-x-1/2 w-55 h-55 pointer-events-none">
              <div className="absolute inset-0">
                <Image
                  src="/icons/crushlevel_heart.svg"
                  alt="Heart pulse 1"
                  fill
                  className="object-cover animate-heart-scale-up-fade opacity-20 scale-[1.6]"
                />
              </div>
              <div className="absolute inset-0">
                <Image
                  src="/icons/crushlevel_heart.svg"
                  alt="Heart pulse 2"
                  fill
                  className="object-cover animate-heart-scale-up-fade-2 opacity-20 scale-[1.6]"
                />
              </div>
            </div>
          )}
          {!noLink ? (
            <Link href={`/@${aiId}`}>
            {/* AI头像 */}
            <Avatar className={cn("size-20 border-2 border-white/20 shadow-lg", size === "large" ? "size-24" : "size-20")}>
              <AvatarImage className="object-cover" src={headImg} />
              <AvatarFallback>
                {nickname?.slice(0, 1)}
              </AvatarFallback>
            </Avatar>
          </Link>) : (
            <Avatar className={cn("size-20 border-2 border-white/20 shadow-lg", size === "large" ? "size-24" : "size-20")}>
              <AvatarImage className="object-cover" src={headImg} />
              <AvatarFallback>
                {nickname?.slice(0, 1)}
              </AvatarFallback>
            </Avatar>
          )}

          {!noLink ? (
            <Link href={`/profile`}>
            {/* 用户头像 */}
            <Avatar className={cn("size-20 border-2 border-white/20 shadow-lg", size === "large" ? "size-24" : "size-20")}>
              <AvatarImage className="object-cover" src={currentUserHeadImg} />
              <AvatarFallback>
                {currentUser?.nickname?.slice(0, 1) || ''}
              </AvatarFallback>
            </Avatar>
          </Link>) : (
            <Avatar className={cn("size-20 border-2 border-white/20 shadow-lg", size === "large" ? "size-24" : "size-20")}>
              <AvatarImage className="object-cover" src={currentUserHeadImg} />
              <AvatarFallback>
                {currentUser?.nickname?.slice(0, 1) || ''}
              </AvatarFallback>
            </Avatar>
          )}

          {/* 中间的心动等级徽章 */}
          <div 
            className={cn(
              "absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 flex flex-col items-center justify-center size-10 z-10 cursor-pointer",
            )}
            onClick={handleRelationTagClick}
          >
            {/* 固定心形徽章底图 */}
            <Image
              src="/icons/crushlevel_heart.svg"
              alt="heart"
              className={cn(
                "absolute top-[20px] -translate-y-1/2 z-[5]",
                isLevelChanging && showAnimation && "animate-heart-badge-scale-down"
              )}
              width={40}
              height={40}
              key={`badge-${animationKey}`}
            />
            
            {/* 等级数字 */}
            {showNumber && (
              <div 
                className={cn(
                  "relative z-10 font-bold transition-all duration-300 txt-numMonotype-m",
                  "animate-fade-in"
                )}
                key={displayLevel}
              >
                {displayLevel?.replace('LEVEL_', '') || '1'}
              </div>
            )}
          </div>
        </div>

        {/* 解锁权益浮窗 */}
        {unlockNotification.show && (
          <div 
            className={cn(
              "absolute left-1/2 -translate-x-1/2 top-full mt-4 z-20",
              unlockNotification.animationState === 'slide-in-up' && "animate-unlock-slide-up",
              unlockNotification.animationState === 'fade-in' && "animate-unlock-fade-in",
              unlockNotification.animationState === 'slide-out-down' && "animate-unlock-slide-down",
              unlockNotification.animationState === 'showing' && "animate-unlock-fade-out"
            )}
          >
            <div className={cn(
              "box-border flex gap-2 items-center justify-center px-4 py-1.5 rounded-full whitespace-nowrap",
              unlockNotification.isUpgrade ? "bg-[#d21f77]" : "bg-warning-normal"
            )}>
              <div className="text-white text-xs font-medium leading-5">
                {unlockNotification.title}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 角色信息 */}
      <div className="flex flex-col items-center gap-2">
        <div className="txt-headline-s text-white text-center">{nickname}</div>
        <div className="cursor-pointer" onClick={handleRelationTagClick}>
          <AIRelationTag showLevel={isShow} heartbeatLevel={heartbeatLevel} heartbeatVal={heartbeatVal} showText={showText} hideIcon={hideIcon} />
        </div>
      </div>
    </div>
  );
}
 
export default CrushLevelAvatar;