'use client'
import { IAlbumItem, LikedStatus, LockStatus } from '@/services/user'
import { useAIUser } from '../context/aiUser'
import { Button, IconButton } from '@/components/ui/button'
import {
  useLikeAlbumImage,
  useSetAlbumImageUnlockMethod,
  useSetDefaultAlbumImage,
} from '@/hooks/aiUser'
import { cn, delay } from '@/lib/utils'
import { Checkbox } from '@/components/ui/checkbox'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { useState, useRef } from 'react'
import AlbumPriceSetting, { AlbumPriceFormData } from '@/components/features/album-price-setting'
import Image from 'next/image'
import AlbumDeleteAlert from '@/components/features/album-delete-alert'
import { formatFromCents } from '@/utils/number'
import { useUpdateWalletBalance } from '@/hooks/useWallet'
import { isChargeDrawerOpenAtom } from '@/atoms/im'
import { useSetAtom } from 'jotai'
import Decimal from 'decimal.js'

const AlbumImageViewerAction = ({
  datas,
  originalDatas,
  currentIndex,
  onDeleted,
  onUnlock,
  unlockingAlbumIdsRef,
}: {
  currentIndex: number
  datas: IAlbumItem[]
  originalDatas: IAlbumItem[]
  onUnlock?: (imageId: number) => Promise<void>
  onDeleted?: (nextIndex: number | null) => void
  unlockingAlbumIdsRef: React.RefObject<Set<number>>
}) => {
  const [lockLoading, setLockLoading] = useState(false)
  const [isDefaultDialogOpen, setIsDefaultDialogOpen] = useState(false)
  const { isOwner, userId } = useAIUser()
  const currentData = datas[currentIndex]
  const { albumId: originalAlbumId } = currentData
  const current = originalDatas.find((item) => item.albumId === originalAlbumId)
  const walletUpdate = useUpdateWalletBalance()
  const setIsChargeDrawerOpen = useSetAtom(isChargeDrawerOpenAtom)

  if (!current) return null
  const { lockStatus, likedStatus, isDefault, unlockPrice, albumId } = current
  const isLiked = likedStatus === LikedStatus.Liked

  const likeMutation = useLikeAlbumImage()
  const setDefaultMutation = useSetDefaultAlbumImage()
  const setAlbumImageUnlockMethodMutation = useSetAlbumImageUnlockMethod()

  const handleLike = (albumId: number, isLiked: boolean) => {
    if (!userId) return
    likeMutation.mutate({
      albumId,
      likedStatus: isLiked ? LikedStatus.Canceled : LikedStatus.Liked,
      aiId: userId,
    })
  }

  const handleSetDefault = (albumId: number) => {
    if (!userId) return
    // 如果是付费图片，则需要弹窗确认
    if (lockStatus) {
      setIsDefaultDialogOpen(true)
      return
    }
    handleConfirmSetDefault(albumId)
  }

  const handleUnlock = async () => {
    if (!userId || lockLoading || unlockingAlbumIdsRef.current?.has(albumId)) return

    if (!walletUpdate.checkSufficient((unlockPrice || 0) / 100)) {
      setIsChargeDrawerOpen(true)
      return
    }

    unlockingAlbumIdsRef.current?.add(albumId)
    setLockLoading(true)

    try {
      await onUnlock?.(albumId)
    } finally {
      setLockLoading(false)
      unlockingAlbumIdsRef.current?.delete(albumId)
    }
  }

  const handleConfirmSetDefault = (albumId: number) => {
    if (!userId) return
    setDefaultMutation.mutate(
      {
        aiId: userId,
        albumId,
      },
      {
        onSuccess: () => {
          setIsDefaultDialogOpen(false)
        },
        onError: () => {
          setIsDefaultDialogOpen(false)
        },
      }
    )
  }

  const handleSetAlbumImageUnlockMethod = async (data: AlbumPriceFormData) => {
    if (!userId) return
    await setAlbumImageUnlockMethodMutation.mutateAsync({
      aiId: userId,
      albumId: datas[currentIndex].albumId,
      unlockPrice: data.price ? new Decimal(data.price).mul(100).toNumber() : 0,
    })
  }

  const renderPayAction = () => {
    if (lockStatus === LockStatus.Lock) {
      return (
        <div className="flex items-center gap-3">
          <div className="txt-label-m text-txt-primary-normal">How to Unlock:</div>
          <div className="flex items-center gap-1">
            <Image src="/icons/diamond.svg" alt="diamond" width={16} height={16} />
            <div className="txt-numMonotype-s text-txt-primary-normal">
              {formatFromCents(unlockPrice)}
            </div>
          </div>
        </div>
      )
    }

    if (isOwner && lockStatus === LockStatus.Unlock) {
      return (
        <div className="flex items-center gap-3">
          <div className="txt-label-m text-txt-primary-normal">How to Unlock:</div>
          <div className="flex items-center gap-1">
            <Image src="/icons/diamond.svg" alt="diamond" width={16} height={16} />
            <div className="txt-numMonotype-s text-txt-primary-normal">
              {formatFromCents(unlockPrice)}
            </div>
          </div>
        </div>
      )
    }
    return <div className="txt-label-m text-txt-primary-normal">How to Unlock: Free</div>
  }

  const renderDefaultAction = () => {
    return (
      <>
        <div className="bg-outline-normal h-6 w-px" />
        <div
          className="bg-surface-element-light-normal flex h-8 cursor-pointer items-center justify-center gap-2 rounded-full px-3 backdrop-blur-lg"
          onClick={() => handleSetDefault(albumId)}
        >
          <Checkbox shape="round" checked={isDefault} />
          <div className="txt-label-s">Default</div>
        </div>
        <AlertDialog open={isDefaultDialogOpen} onOpenChange={setIsDefaultDialogOpen}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Default image</AlertDialogTitle>
            </AlertDialogHeader>
            <AlertDialogDescription>
              After setting this as the default image, its unlock method can only be "Free."
            </AlertDialogDescription>
            <AlertDialogFooter>
              <AlertDialogCancel>Cancel</AlertDialogCancel>
              <Button
                variant="primary"
                loading={setDefaultMutation.isPending}
                onClick={() => handleConfirmSetDefault(albumId)}
              >
                Confirm
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
        {!isDefault && <div className="bg-outline-normal h-6 w-px" />}
        {!isDefault && (
          <div className="flex items-center gap-3">
            {renderPayAction()}
            <AlbumPriceSetting
              defaultUnlockPrice={unlockPrice || 0}
              onConfirm={handleSetAlbumImageUnlockMethod}
            />
          </div>
        )}
        <div className="bg-outline-normal h-6 w-px" />
        <AlbumDeleteAlert
          aiId={userId!}
          albumId={albumId}
          isDefaultImage={!!isDefault}
          onDeleted={() => {
            const nextLength = datas.length - 1
            if (nextLength <= 0) {
              onDeleted?.(null)
              return
            }
            const isLast = currentIndex >= nextLength
            const nextIndex = isLast ? nextLength - 1 : currentIndex
            onDeleted?.(nextIndex)
          }}
        >
          <IconButton iconfont="icon-trashcan" variant="tertiary" size="small" />
        </AlbumDeleteAlert>
      </>
    )
  }

  if (!isOwner) {
    if (!lockStatus || lockStatus === LockStatus.Unlock) {
      // 没有上锁的图片，显示点赞按钮
      return (
        <>
          <div className="bg-outline-normal h-6 w-px" />
          <Button
            variant="tertiary"
            size="small"
            className="gap-1"
            onClick={() => handleLike(datas[currentIndex].albumId, isLiked)}
          >
            <i
              className={cn('iconfont !text-[16px] leading-none', {
                'icon-Like': !isLiked,
                'icon-Like-fill !text-important-normal': isLiked,
              })}
            />
            <div className="txt-label-s">Like</div>
          </Button>
        </>
      )
    }

    return (
      <>
        <div className="bg-outline-normal h-6 w-px" />
        <Button
          variant="primary"
          size="small"
          className="gap-1"
          onClick={handleUnlock}
          loading={lockLoading}
        >
          Unlock
        </Button>
      </>
    )
  }

  return <>{renderDefaultAction()}</>
}

export default AlbumImageViewerAction
