import Image from 'next/image'
import {
  InlineDrawer,
  InlineDrawerContent,
  InlineDrawerDescription,
  InlineDrawerFooter,
  InlineDrawerHeader,
} from './InlineDrawer'
import { Button } from '@/components/ui/button'
import { useAtom, useSetAtom } from 'jotai'
import { isCrushLevelRetrieveDrawerOpenAtom, createDrawerOpenState } from '@/atoms/chat'
import { useBuyHeartbeat, useGetHeartbeatLevel } from '@/hooks/useIm'
import { useChatConfig } from '../../context/chatConfig'
import numeral from 'numeral'
import { formatFromCents } from '@/utils/number'
import React, { useEffect } from 'react'
import { useGetWalletBalance, useUpdateWalletBalance } from '@/hooks/useWallet'
import { isChargeDrawerOpenAtom } from '@/atoms/im'
import { useQueryClient } from '@tanstack/react-query'
import { imKeys, walletKeys } from '@/lib/query-keys'

const CrushLevelRetrieveDrawer = () => {
  // 图片加载状态管理
  const [isBgTopLoaded, setIsBgTopLoaded] = React.useState(false)
  const [showHeartImage, setShowHeartImage] = React.useState(false)
  const [loading, setLoading] = React.useState(false)
  const [drawerState, setDrawerState] = useAtom(isCrushLevelRetrieveDrawerOpenAtom)
  const isCrushLevelRetrieveDrawerOpen = drawerState.open
  const setIsCrushLevelRetrieveDrawerOpen = (open: boolean) =>
    setDrawerState(createDrawerOpenState(open))
  const { aiId, aiInfo } = useChatConfig()

  const { data, refetch } = useGetHeartbeatLevel({ aiId: Number(aiId) })
  const { heartbeatLeveLDictList } = data || {}
  const { aiUserHeartbeatRelation } = aiInfo || {}
  const { subtractHeartbeatVal, heartbeatVal, price } = aiUserHeartbeatRelation || {}

  const { mutateAsync: retrieveHeartbeatVal, isPending: isRetrieveHeartbeatValPending } =
    useBuyHeartbeat({ aiId: Number(aiId) })
  const { data: walletData } = useGetWalletBalance()
  const walletUpdate = useUpdateWalletBalance()
  const setIsChargeDrawerOpen = useSetAtom(isChargeDrawerOpenAtom)
  const queryClient = useQueryClient()

  const handleRetrieveHeartbeatVal = async () => {
    if (loading) return

    try {
      setLoading(true)
      if (
        !walletUpdate.checkSufficient(
          Math.max((price || 0) * (subtractHeartbeatVal || 0), 100) / 100
        )
      ) {
        setIsChargeDrawerOpen(true)
        return
      }
      await retrieveHeartbeatVal({ aiId: Number(aiId), heartbeatVal: subtractHeartbeatVal || 0 })
      await queryClient.invalidateQueries({ queryKey: imKeys.heartbeatLevel(Number(aiId)) })
      await queryClient.invalidateQueries({ queryKey: imKeys.imUserInfo(Number(aiId)) })
      await queryClient.invalidateQueries({ queryKey: walletKeys.getWalletBalance() })
      setIsCrushLevelRetrieveDrawerOpen(false)
    } catch (error) {
      setLoading(false)
    } finally {
      setLoading(false)
    }
  }

  // 计算心的位置
  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 (isCrushLevelRetrieveDrawerOpen) {
      refetch()
      // 重置图片加载状态
      setIsBgTopLoaded(false)
      setShowHeartImage(false)
      queryClient.invalidateQueries({ queryKey: walletKeys.getWalletBalance() })
    }
  }, [isCrushLevelRetrieveDrawerOpen, 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)
  }

  return (
    <InlineDrawer
      id="crushLevelRetrieve"
      open={isCrushLevelRetrieveDrawerOpen}
      onOpenChange={setIsCrushLevelRetrieveDrawerOpen}
      timestamp={drawerState.timestamp}
    >
      <InlineDrawerContent>
        <div className="absolute top-0 right-0 left-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="animate-in fade-in-0 slide-in-from-bottom-4 absolute left-1/2 -translate-x-1/2 transition-all duration-500 ease-in-out"
              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="absolute inset-0 flex flex-col">
          <InlineDrawerHeader> </InlineDrawerHeader>
          <InlineDrawerDescription>
            <div className="pt-[124px]">
              <div className="txt-title-m text-center">Recover Crush Value</div>
              <div className="mt-6">
                <div className="flex items-center justify-between py-3">
                  <div className="txt-label-l flex-1">Price per Unit</div>
                  <div className="txt-numMonotype-s flex items-center gap-2">
                    <Image src="/icons/diamond.svg" alt="Crush Level" width={16} height={16} />
                    <div>{formatFromCents(price || 0)}/&#8451;</div>
                  </div>
                </div>
                <div className="flex items-center justify-between py-3">
                  <div className="txt-label-l flex-1">Quantity</div>
                  <div className="txt-numMonotype-s flex items-center gap-2">
                    {/* <Image src="/icons/diamond.svg" alt="Crush Level" width={16} height={16} /> */}
                    <div>{subtractHeartbeatVal}&#8451;</div>
                  </div>
                </div>
                <div className="flex items-center justify-between py-3">
                  <div className="txt-label-l flex-1">Total</div>
                  <div className="txt-numMonotype-s flex items-center gap-2">
                    <Image src="/icons/diamond.svg" alt="Crush Level" width={16} height={16} />
                    <div>
                      {formatFromCents(Math.max((price || 0) * (subtractHeartbeatVal || 0), 100))}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </InlineDrawerDescription>
          <InlineDrawerFooter>
            <Button
              variant="tertiary"
              size="large"
              onClick={() => {
                setIsCrushLevelRetrieveDrawerOpen(false)
              }}
            >
              Cancel
            </Button>
            <Button
              variant="primary"
              size="large"
              onClick={handleRetrieveHeartbeatVal}
              loading={loading}
            >
              Purchase
            </Button>
          </InlineDrawerFooter>
        </div>
      </InlineDrawerContent>
    </InlineDrawer>
  )
}

export default CrushLevelRetrieveDrawer
