'use client'

import { ExtendedMessage, isChargeDrawerOpenAtom } from '@/atoms/im'
import { Button } from '@/components/ui/button'
import { ImageViewer } from '@/components/ui/image-viewer'
import { useUnlockAlbumImage, useUnlockImage, useViewUnlockAlbumImage } from '@/hooks/aiUser'
import { useImageViewer } from '@/hooks/useImageViewer'
import Image from 'next/image'
import { toast } from 'sonner'
import { useEffect, useState } from 'react'
import { formatFromCents } from '@/utils/number'
import { useUpdateWalletBalance } from '@/hooks/useWallet'
import { useSetAtom } from 'jotai'

const AlbumImageViewerAction = ({
  aiId,
  albumId,
  messageServerId,
  onUnlockSuccess,
  unlockPrice,
}: {
  aiId: number
  albumId: number
  messageServerId: string
  unlockPrice: number
  onUnlockSuccess?: ({ img1, img2, img3 }: { img1: string; img2: string; img3: string }) => void
}) => {
  const { mutateAsync: unlockAlbumImage, isPending: isUnlocking } = useUnlockImage()
  const walletUpdate = useUpdateWalletBalance()
  const setIsChargeDrawerOpen = useSetAtom(isChargeDrawerOpenAtom)

  const handleUnlock = async () => {
    try {
      if (!walletUpdate.checkSufficient((unlockPrice || 0) / 100)) {
        setIsChargeDrawerOpen(true)
        return
      }
      const resp = await unlockAlbumImage({ aiId, albumId: Number(albumId), messageServerId })
      toast.success('Unlock success')
      // 解锁成功后调用回调函数
      onUnlockSuccess?.(resp)
    } catch (error) {
      toast.error('Unlock failed')
      console.error('解锁失败:', error)
    }
  }

  return (
    <>
      <Button variant="primary" size="small" onClick={handleUnlock} loading={isUnlocking}>
        Unlock
      </Button>
    </>
  )
}

const ChatUnlockImageItem = ({
  message,
  customData,
}: {
  message: ExtendedMessage
  customData: {
    albumId: string
    url: string
    unlockPrice: number
  }
}) => {
  const { albumId, url, unlockPrice } = customData || {}

  // 状态管理
  const [isActuallyLocked, setIsActuallyLocked] = useState<boolean | null>(null) // null表示未检查，true表示上锁，false表示已解锁
  const [checkedImages, setCheckedImages] = useState<{
    img1?: string
    img2?: string
    img3?: string
  }>({})
  const [isChecking, setIsChecking] = useState(false)

  // hooks
  const { mutateAsync: viewUnlockAlbumImage } = useViewUnlockAlbumImage()

  // 图片查看器
  const {
    isOpen: isViewerOpen,
    currentIndex: viewerIndex,
    openViewer,
    closeViewer,
    handleIndexChange,
  } = useImageViewer()

  // 检查图片解锁状态
  const checkUnlockStatus = async () => {
    if (isChecking) return // 防止重复请求

    setIsChecking(true)
    try {
      const result = await viewUnlockAlbumImage({
        aiId: Number(message.senderId.split('@')[0]),
        albumId: Number(albumId),
        messageServerId: message.messageServerId,
      })

      // 如果接口返回了解锁后的图片，说明图片已经解锁
      if (result && (result.img1 || result.img2 || result.img3)) {
        setIsActuallyLocked(false)
        setCheckedImages(result)
      } else {
        setIsActuallyLocked(true)
      }
    } catch (error) {
      // 如果接口出错，保持锁定状态
      console.error('检查图片解锁状态失败:', error)
      setIsActuallyLocked(true)
    } finally {
      setIsChecking(false)
    }
  }

  // 处理解锁成功后的状态刷新
  const handleUnlockSuccess = ({
    img1,
    img2,
    img3,
  }: {
    img1: string
    img2: string
    img3: string
  }) => {
    setCheckedImages({ img1, img2, img3 })
    setIsActuallyLocked(false)
  }

  const handleClick = async () => {
    // 如果还没有检查过解锁状态，先检查
    if (isActuallyLocked === null) {
      await checkUnlockStatus()
    }

    // 根据检查结果决定显示的图片
    const imagesToShow =
      isActuallyLocked === false && checkedImages.img1
        ? [checkedImages.img3].filter((img): img is string => Boolean(img))
        : [url]
    openViewer(imagesToShow, 0)
  }

  return (
    <>
      <div
        className="relative h-[160px] w-[160px] cursor-pointer overflow-hidden rounded-lg"
        onClick={handleClick}
      >
        <img src={url} className="h-full w-full object-cover" alt="" />
        {/* 只有在确认图片已解锁时才不显示遮罩，未检查或上锁时都显示遮罩 */}
        {
          <div className="absolute inset-0 flex flex-col items-center justify-center gap-4 bg-black/20">
            <i className="iconfont icon-private-border !text-[24px] leading-none" />
            <div className="txt-label-m flex items-center gap-1">
              <div className="relative h-4 w-4">
                <Image src="/icons/diamond.svg" alt="diamond" fill className="object-contain" />
              </div>
              <span>{`${formatFromCents(unlockPrice || 0)} unlock`}</span>
            </div>
          </div>
        }
        {/* Loading状态覆盖层 */}
        {isChecking && (
          <div className="absolute inset-0 flex items-center justify-center bg-black/60">
            <div className="h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white" />
          </div>
        )}
      </div>
      <div className="h-8" />

      <ImageViewer
        images={
          isActuallyLocked === false && checkedImages.img1
            ? [checkedImages.img1, checkedImages.img2, checkedImages.img3].filter(
                (img): img is string => Boolean(img)
              )
            : [url]
        }
        currentIndex={0}
        open={isViewerOpen}
        onClose={closeViewer}
        onIndexChange={handleIndexChange}
        showChooseButton={false}
        showPagination={false}
        ActionComponent={() => {
          // 只有在确认图片上锁时才显示解锁按钮
          if (isActuallyLocked !== true) {
            return null
          }
          return (
            <AlbumImageViewerAction
              aiId={Number(message.senderId.split('@')[0])}
              albumId={Number(albumId)}
              unlockPrice={unlockPrice}
              messageServerId={message.messageServerId}
              onUnlockSuccess={handleUnlockSuccess}
            />
          )
        }}
        OverlayComponent={() => {
          // 只有在确认图片上锁且有解锁价格时才显示覆盖层
          if (isActuallyLocked !== true || !unlockPrice) {
            return null
          }
          return (
            <div className="absolute inset-0 z-5 flex flex-col items-center justify-center gap-6 bg-black/15 backdrop-blur-3xl">
              <i className="iconfont icon-private !text-[48px] leading-none" />
              <div className="flex items-center gap-2">
                <Image src="/icons/diamond.svg" alt="diamond" width={32} height={32} />
                <div className="txt-title-m">{`${formatFromCents(unlockPrice || 0)} to unlock`}</div>
              </div>
            </div>
          )
        }}
      />
    </>
  )
}

export default ChatUnlockImageItem
