import React from "react";
import { InlineDrawer, InlineDrawerContent, InlineDrawerDescription, InlineDrawerHeader } from "../InlineDrawer";
import { IconButton, Button } from "@/components/ui/button";
import Image from "next/image";
import CrushLevelAvatarGroup from "./CrushLevelAvatarGroup";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Switch } from "@/components/ui/switch";
import { useAtom, useSetAtom } from "jotai";
import { isCrushLevelDrawerOpenAtom, isCrushLevelRetrieveDrawerOpenAtom, createDrawerOpenState } from "@/atoms/chat";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useGetHeartbeatLevel, useSetShowRelationship } from "@/hooks/useIm";
import { useChatConfig } from "../../../context/chatConfig";
import HeartList from "./HeartList";
import { useHeartLevelTextFromLevel } from "@/hooks/useHeartLevel";
import numeral from "numeral";
import { imKeys } from "@/lib/query-keys";
import { useQueryClient } from "@tanstack/react-query";
import { headerLevelDictMap } from "@/components/features/AIRelationTag";

const CrushLevelDrawer = () => {
  const [drawerState, setDrawerState] = useAtom(isCrushLevelDrawerOpenAtom);
  const isCrushLevelDrawerOpen = drawerState.open;
  const setIsCrushLevelDrawerOpen = (open: boolean) => setDrawerState(createDrawerOpenState(open));
  const setRetrieveDrawerState = useSetAtom(isCrushLevelRetrieveDrawerOpenAtom);
  const setIsCrushLevelRetrieveDrawerOpen = (open: boolean) => setRetrieveDrawerState(createDrawerOpenState(open));
  const { aiId, aiInfo } = useChatConfig();
  const queryClient = useQueryClient();

  // 图片加载状态管理
  const [isBgTopLoaded, setIsBgTopLoaded] = React.useState(false);
  const [showHeartImage, setShowHeartImage] = React.useState(false);

  const { aiUserHeartbeatRelation } = aiInfo || {};

  const { data, refetch } = useGetHeartbeatLevel({ 
    aiId: Number(aiId),
    enabled: false // 禁用自动查询，手动控制何时获取数据
  });
  const { heartbeatLeveLDictList } = data || {};
  const { heartbeatLevel, heartbeatVal, heartbeatScore, dayCount, subtractHeartbeatVal, isShow } = aiUserHeartbeatRelation || {};
  const heartLevelText = useHeartLevelTextFromLevel(heartbeatLevel);

  const { mutate: setShowRelationship, isPending: isSetShowRelationshipPending } = useSetShowRelationship({ aiId: Number(aiId) });

  // 计算心的位置
  const calculateHeartPosition = () => {
    const defaultTop = 150;
    if (!heartbeatVal || !heartbeatLeveLDictList || heartbeatLeveLDictList.length === 0) {
      return defaultTop; // 默认位置
    }

    // 获取最低等级的起始值和最高等级的起始值
    const sortedLevels = [...heartbeatLeveLDictList].sort((a, b) => (a.startVal || 0) - (b.startVal || 0));
    const minStartVal = sortedLevels[0]?.startVal || 0;
    const maxStartVal = sortedLevels[sortedLevels.length - 1]?.startVal || 0;
    
    // 如果只有一个等级或者最大最小值相等，使用默认位置
    if (maxStartVal <= minStartVal) {
      return defaultTop;
    }

    // 计算当前心动值在整个等级系统中的总进度（0-1）
    const totalProgress = Math.max(0, Math.min(1, (heartbeatVal - minStartVal) / (maxStartVal - minStartVal)));

    // 将总进度映射到位置范围：top 75（空心）到 top 150（全心）
    const minTop = defaultTop; // 空心位置
    const maxTop = 75; // 全心位置
    const calculatedTop = minTop + (totalProgress * (maxTop - minTop));

    return calculatedTop;
  };

  const heartTop = calculateHeartPosition();

  // 根据位置决定心的显示状态
  const getHeartImageSrc = () => {
    // top 75为空心，top 150为全心
    // 根据位置变化动态调整心的显示状态
    
    // 目前只有一个心的图片，可以通过透明度或其他CSS属性来模拟空心/全心效果
    // 或者后续可以添加不同的图片资源
    return "/images/crushlevel/heart.png";
  };

  // 当抽屉打开时获取心动等级数据
  React.useEffect(() => {
    if (isCrushLevelDrawerOpen) {
      refetch();
      // 重置图片加载状态
      setIsBgTopLoaded(false);
      setShowHeartImage(false);
    }
  }, [isCrushLevelDrawerOpen, refetch]);

  // 处理 bg-top 图片加载完成后的延迟显示逻辑
  React.useEffect(() => {
    if (isBgTopLoaded) {
      // bg-top 加载完成后延迟 300ms 显示心形图片
      const timer = setTimeout(() => {
        setShowHeartImage(true);
      }, 300);
      
      return () => clearTimeout(timer);
    }
  }, [isBgTopLoaded]);

  // bg-top 图片加载完成的处理函数
  const handleBgTopLoad = () => {
    setIsBgTopLoaded(true);
  };

  const renderLineText = () => {
    if (!heartbeatVal) {
      return (
        <div className="flex items-center gap-2 w-full">
          <div className="flex-1 h-px bg-outline-normal" />
          <span className="txt-title-m">No Crush Connection Yet</span>
          <div className="flex-1 h-px bg-outline-normal" />
        </div>
      )
    }

    if (heartbeatLevel && isShow) {
      return (
        <div className="flex items-center gap-2 w-full">
          <div className="flex-1 h-px bg-outline-normal" />
          <span className="txt-display-s">· {headerLevelDictMap[heartbeatLevel]?.title} ·</span>
          <div className="flex-1 h-px bg-outline-normal" />
        </div>
      )
    }

    return null;
  }

  return (
    <InlineDrawer
      id="crushLevel"
      open={isCrushLevelDrawerOpen}
      onOpenChange={setIsCrushLevelDrawerOpen}
      timestamp={drawerState.timestamp}
    >
      <InlineDrawerContent className="overflow-y-auto">
        {/* 紫色渐变背景 */}
        <div className="absolute top-0 left-0 right-0 h-[480px] overflow-hidden">
          <Image src="/images/crushlevel/bg-bottom.png" alt="CrushLevel" fill className="object-cover" />
          {/* 心形图片 - 只在 bg-top 加载完成后延迟显示 */}
          {showHeartImage && (
            <Image 
              src={getHeartImageSrc()} 
              alt="Crush Level" 
              className="absolute left-1/2 -translate-x-1/2 transition-all duration-500 ease-in-out animate-in fade-in-0 slide-in-from-bottom-4" 
              width={124} 
              height={124} 
              style={{ 
                top: `${heartTop}px`,
              }} 
            />
          )}
          <Image 
            src="/images/crushlevel/bg-top.png" 
            alt="Crush Level" 
            fill 
            className="object-cover" 
            onLoad={handleBgTopLoad}
          />
        </div>

        <div className="relative inset-0">
          <InlineDrawerHeader>
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-1">
                <div className="txt-title-m">CrushLevel</div>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <IconButton
                      iconfont="icon-question" 
                      variant="tertiaryDark" 
                      size="mini" 
                    />
                  </TooltipTrigger>
                  <TooltipContent>
                    <div className="w-64 space-y-2">
                      <p>* Increase your Crush Value by chatting or sending gifts. If you don’t interact for 24 hours, your Crush Value may gradually decrease.</p>
                      <p>* Your virtual character’s emotional responses during conversations will affect whether the Crush Value goes up or down.</p>
                      <p>* A higher Crush Value boosts your Crush Level, unlocking new titles, features, and relationship stages with your character.</p>
                    </div>
                  </TooltipContent>
                </Tooltip>
              </div>

              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <IconButton 
                    iconfont="icon-More" 
                    variant="ghost" 
                    size="small" 
                  />
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem 
                    onClick={(e) => {
                      e.preventDefault(); // 阻止默认行为
                      e.stopPropagation(); // 阻止事件冒泡
                      
                      if (isSetShowRelationshipPending) return;
                      queryClient.setQueryData(imKeys.heartbeatLevel(aiId), (old: any) => {
                        return {
                          ...old,
                          aiUserHeartbeatRelation: {
                            ...old.aiUserHeartbeatRelation,
                            isShow: !old.aiUserHeartbeatRelation.isShow
                          }
                        }
                      })
                      queryClient.setQueryData(imKeys.imUserInfo(aiId), (old: any) => {
                        return {
                          ...old,
                          aiUserHeartbeatRelation: {
                            ...old.aiUserHeartbeatRelation,
                            isShow: !old.aiUserHeartbeatRelation.isShow
                          }
                        }
                      })
                      setShowRelationship({ aiId: Number(aiId), isShow: !isShow });
                    }}
                    onSelect={(e) => {
                      e.preventDefault(); // 阻止 onSelect 默认关闭行为
                    }}
                  >
                    <div className="w-full flex items-center justify-between">
                      <div className="txt-body-l flex-1">Hide Relationship</div>
                      <Switch size="sm" className="cursor-pointer" checked={!isShow} disabled={isSetShowRelationshipPending} />
                    </div>
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </InlineDrawerHeader>
          <CrushLevelAvatarGroup />
          <div>
            {/* 等级和温度信息 */}
            <div className="flex flex-col items-center gap-4 px-6">
              {heartbeatVal ? <div className="flex items-center gap-2 txt-numDisplay-s">
                <span>{heartLevelText || 'Lv.0'}</span>
                <div className="w-px h-[18px] bg-outline-normal" />
                <span>
                  {heartbeatVal || 0}<span className="txt-numMonotype-s">&#8451;</span>
                </span>
              </div> : (
                <div className="px-6 text-center">
                  <span className="txt-numDisplay-s">
                    {heartbeatVal || 0}<span className="txt-numMonotype-s">&#8451;</span>
                  </span>
                </div>
              )}
              
              {/* Meet 分割线 */}
              {renderLineText()}
              
              {/* 描述文本 */}
              {!!heartbeatVal && <p className="txt-body-s">
                {`Known for ${Math.max((dayCount || 0), 1)} days | Crush Value higher than ${numeral(heartbeatScore).format("0.00%")} of users`}
              </p>}
            </div>
          </div>

          {!!subtractHeartbeatVal && <div className="px-6 my-6">
            <div className="bg-surface-element-normal rounded-m p-4 flex justify-between items-center gap-2">
              <div className="flex-1 txt-body-s">{`Crush Value lost: -${subtractHeartbeatVal}℃`}</div>
              <Button variant="ghost" size="small" onClick={() => {
                setIsCrushLevelRetrieveDrawerOpen(true);
              }}>
                Retrieve
              </Button>
            </div>
          </div>}

          {/* 权限卡片网格 */}
          <InlineDrawerDescription className="pb-6">
            <HeartList datas={heartbeatLeveLDictList} />
          </InlineDrawerDescription>
        </div>
      </InlineDrawerContent>
    </InlineDrawer>
  );
};

export default CrushLevelDrawer;