import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useParams } from "next/navigation";
import { useSetAtom } from "jotai";
import { isCrushLevelDrawerOpenAtom, createDrawerOpenState } from "@/atoms/chat";
import { useState, useEffect, useRef } from "react";
import { cn } from "@/lib/utils";
import Image from "next/image";
import { useChatConfig } from "../context/chatConfig";
import AIRelationTag from "@/components/features/AIRelationTag";

const CrushLevelAction = () => {
  const { aiId } = useParams();
  const { aiInfo } = useChatConfig();
  const setDrawerState = useSetAtom(isCrushLevelDrawerOpenAtom);
  const setIsCrushLevelDrawerOpen = (open: boolean) => setDrawerState(createDrawerOpenState(open));

  const { headImg, nickname, aiUserHeartbeatRelation } = aiInfo || {};
  const { heartbeatLevel, heartbeatVal, heartbeatLevelName, title } = aiUserHeartbeatRelation || {};

  // 升级降级动画状态
  const [animationKey, setAnimationKey] = useState(0);
  const [displayLevel, setDisplayLevel] = useState(heartbeatLevel);
  const [isFirstLoad, setIsFirstLoad] = useState(true);
  const [currentAiId, setCurrentAiId] = useState(aiId); // 追踪当前的 aiId
  const [isAiSwitching, setIsAiSwitching] = useState(false); // 标记是否正在切换AI
  const [unlockNotification, setUnlockNotification] = useState<{
    show: boolean;
    isUpgrade: boolean;
    title: string;
    animationState: 'slide-in-up' | 'showing' | 'fade-out' | 'hidden';
  }>({
    show: false,
    isUpgrade: true,
    title: '',
    animationState: 'hidden'
  });

  // 用于管理解锁权益浮窗定时器的引用
  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 切换时，清除所有定时器和状态
      setIsAiSwitching(true);
      clearUnlockNotificationTimers();
      setAnimationKey(0); // 重置动画key
      setIsFirstLoad(true);
      setDisplayLevel(heartbeatLevel);
      setCurrentAiId(aiId);
      
      // 短暂延迟后重置切换标记
      setTimeout(() => {
        setIsAiSwitching(false);
      }, 100);
    }
  }, [aiId, currentAiId, heartbeatLevel]);

  // 监听等级变化事件触发动画
  useEffect(() => {
    const handleLevelChange = (event: CustomEvent) => {
      const { type, aiId: eventAiId, newLevel, title: eventTitle } = event.detail;
      
      // 只处理当前AI的等级变化事件
      if (`${eventAiId}` === `${aiId}`) {
        // 清除之前的解锁权益浮窗状态和定时器
        clearUnlockNotificationTimers();
        
        setAnimationKey(prev => prev + 1);
        
        // 判断是升级还是降级
        const isUpgrade = type === 'up';
        const newLevelNumber = newLevel?.replace('LEVEL_', '') || '1';
        
        // 更新显示等级
        setDisplayLevel(newLevel);
        
        // 显示解锁权益浮窗
        unlockNotificationTimersRef.current.showTimer = setTimeout(() => {
          setUnlockNotification({
            show: true,
            isUpgrade,
            title: eventTitle || (isUpgrade ? `Unlocked "Level ${newLevelNumber}" title` : `Lost "Level ${displayLevel?.replace('LEVEL_', '') || '1'}" privilege`),
            animationState: 'slide-in-up'
          });
        }, 300);
      }
    };

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

    return () => {
      // 清理事件监听器
      window.removeEventListener('heartbeat-level-change', handleLevelChange as EventListener);
    };
  }, [aiId, 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') {
      // 清除之前的hideTimer（如果有的话）
      if (unlockNotificationTimersRef.current.hideTimer) {
        clearTimeout(unlockNotificationTimersRef.current.hideTimer);
      }
      
      // 滑入完成后，保持显示3秒
      unlockNotificationTimersRef.current.hideTimer = setTimeout(() => {
        setUnlockNotification(prev => ({
          ...prev,
          animationState: 'showing'
        }));
      }, 3000);
    } else if (unlockNotification.animationState === 'showing') {
      // 显示3秒后淡出
      const timer = setTimeout(() => {
        setUnlockNotification(prev => ({
          ...prev,
          animationState: 'fade-out'
        }));
      }, 300);

      return () => clearTimeout(timer);
    } else if (unlockNotification.animationState === 'fade-out') {
      // 淡出后隐藏
      const timer = setTimeout(() => {
        setUnlockNotification({
          show: false,
          isUpgrade: true,
          title: '',
          animationState: 'hidden'
        });
        unlockNotificationTimersRef.current.hideTimer = undefined;
      }, 300);

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

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

  // 获取心动等级数字
  const levelNumber = displayLevel?.replace('LEVEL_', '') || '1';

  if (!heartbeatLevel) {
    return null;
  }

  return (
    <div className="absolute top-0 left-0">
      <div
        className="w-32 h-32 absolute top-0 left-0 p-6 cursor-pointer z-10"
        style={{ background: "radial-gradient(98.91% 98.91% at 0% 0%, #F264A4 0%, rgba(194, 65, 230, 0.00) 100%)" }}
        onClick={() => {
          setIsCrushLevelDrawerOpen(true);
        }}
      >
        <div></div>
        {/* 头像容器 */}
        <div className="w-12 h-12 relative">
          <Avatar className="w-12 h-12">
            <AvatarImage src={headImg} className="object-cover" />
            <AvatarFallback>
              {nickname?.slice(0, 1)}
            </AvatarFallback>
          </Avatar>
          
          {/* 心动等级外圈 */}
          {heartbeatLevel && (
            <div className="absolute -top-1 -left-1 w-14 h-14">
              <svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" viewBox="0 0 56 56" fill="none">
                <path d="M55 28C55 31.5457 54.3016 35.0567 52.9447 38.3325C51.5879 41.6082 49.5991 44.5847 47.0919 47.0919C44.5847 49.5991 41.6082 51.5879 38.3325 52.9447C35.0567 54.3016 31.5457 55 28 55C24.4543 55 20.9433 54.3016 17.6675 52.9447C14.3918 51.5879 11.4153 49.5991 8.90812 47.0919C6.40093 44.5847 4.41213 41.6082 3.05525 38.3325C1.69838 35.0567 1 31.5457 1 28C1 24.4543 1.69838 20.9433 3.05525 17.6675C4.41213 14.3918 6.40094 11.4153 8.90812 8.90811C11.4153 6.40093 14.3918 4.41213 17.6676 3.05525C20.9433 1.69837 24.4543 1 28 1C31.5457 1 35.0567 1.69838 38.3325 3.05525C41.6082 4.41213 44.5847 6.40094 47.0919 8.90812C49.5991 11.4153 51.5879 14.3918 52.9447 17.6676C54.3016 20.9433 55 24.4543 55 28L55 28Z" stroke="#F264A4" strokeWidth="2" strokeLinecap="round"/>
              </svg>
            </div>
          )}
          
          {/* 心动等级徽章 */}
          {heartbeatLevel && (
            <div className="absolute -top-2 -right-2 w-6 h-6 flex items-center justify-center">
              {/* 心形背景 */}
              <div className="absolute inset-0">
                <Image
                  src="/icons/crushlevel_heart.svg"
                  alt="Heart"
                  fill
                  className="object-contain"
                />
              </div>
              {/* 等级数字 */}
              <div className="relative z-10 text-white text-center txt-numMonotype-xs">
                {levelNumber}
              </div>
            </div>
          )}

          {/* 温度标签 */}
          {!!heartbeatVal && heartbeatLevel && (
            <div className="absolute -bottom-3 left-1/2 -translate-x-1/2">
              <AIRelationTag heartbeatVal={heartbeatVal} heartbeatLevel={heartbeatLevel} showLevel={false} hideIcon size="mini" />
            </div>
          )}
        </div>
      </div>

      {/* 解锁权益浮窗 */}
      {unlockNotification.show && (
        <div 
          className={cn(
            "absolute left-[87px] top-4 z-20 max-w-[480px]",
            unlockNotification.animationState === 'slide-in-up' && "animate-unlock-slide-up",
            unlockNotification.animationState === 'fade-out' && "animate-unlock-fade-out"
          )}
        >
          <div className={cn(
            "px-3 py-1.5 h-6 flex items-center justify-start gap-2",
            unlockNotification.isUpgrade ? "bg-primary-normal" : "bg-warning-normal"
          )}
          style={{
            borderRadius: '12px 12px 12px 0'
          }}>
            <div className="text-white txt-label-s whitespace-nowrap">
              {unlockNotification.title}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
 
export default CrushLevelAction;