'use client'

import { useTransactionListWithInfiniteScroll } from '@/hooks/useWallet'
import { TransactionType, BizType, BillOutput } from '@/services/wallet/types'
import { formatFromCents } from '@/utils/number'
import Image from 'next/image'
import { InfiniteScrollList } from '@/components/ui/infinite-scroll-list'
import Empty from '@/components/ui/empty'
import { useCreateDict } from '@/hooks/create'
import { useGetGiftList } from '@/hooks/useIm'
import { GiftOutput } from '@/services/im'

// 收入类型图标映射
const getIncomeIcon = (bizType: BizType, extend: string, giftList: GiftOutput[]) => {
  switch (bizType) {
    case BizType.Gift:
      const giftId = extend ? JSON.parse(extend).giftId : undefined
      if (giftId) {
        const gift = giftList.find((gift) => gift.id === giftId)
        if (gift) {
          return gift.icon
        }
        return ''
      }
      return '/images/wallet/icon-image.png'
    case BizType.CreateAIImage:
    case BizType.ImageUnlock:
      return '/images/wallet/icon-image.png' // 图片相关图标
    case BizType.VoiceCall:
    case BizType.SendVoice:
      return '/images/creator/icon-star.png' // 语音相关图标
    case BizType.SubscribeMember:
    case BizType.Sub:
      return '/images/creator/icon-more.png' // 订阅图标
    default:
      return '/icons/diamond.svg' // 默认钻石图标
  }
}

// 收入类型标题映射
const getIncomeTitle = (bizType: BizType, extend: string, giftList: GiftOutput[]) => {
  switch (bizType) {
    case BizType.Gift:
      const giftId = extend ? JSON.parse(extend).giftId : undefined
      if (giftId) {
        const gift = giftList.find((gift) => gift.id === giftId)
        if (gift) {
          return gift.name
        }
      }
      return 'Gift'
    case BizType.CreateAIImage:
      return 'AI Image'
    case BizType.ImageUnlock:
      return 'Image'
    case BizType.VoiceCall:
      return 'Voice Call'
    case BizType.SendVoice:
      return 'Voice Message'
    case BizType.SubscribeMember:
    case BizType.Sub:
      return 'Subscription'
    case BizType.Game:
      return 'Game'
    case BizType.ChatAssistant:
      return 'Chat'
    default:
      return 'Income'
  }
}

// 格式化时间
const formatTime = (timeString?: string) => {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    return date.toLocaleDateString('en-US', {
      month: 'short',
      day: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: true,
    })
  } catch {
    return timeString
  }
}

// 收入项组件
const IncomeItem = ({
  transaction,
  giftList,
}: {
  transaction: BillOutput
  giftList: GiftOutput[]
}) => {
  const { bizType, extend, message, item, nickname } = transaction

  const getDisplayTitle = (): string => {
    if (bizType === BizType.Gift) {
      const giftId = extend ? JSON.parse(extend).giftId : undefined
      if (giftId) {
        const gift = giftList.find((gift) => gift.id === giftId)
        if (gift) {
          return gift.name
        }
      }
    }
    if (message) return message
    if (item) return item
    return getIncomeTitle(transaction.bizType!, transaction.extend || '', giftList)
  }

  return (
    <div className="flex w-full items-center justify-between">
      {/* 左侧：图标和信息 */}
      <div className="flex flex-1 items-center gap-3">
        <div className="bg-surface-nest-normal flex h-16 w-16 items-center justify-center rounded-lg p-1">
          <Image
            src={getIncomeIcon(transaction.bizType!, transaction.extend || '', giftList)}
            alt={getDisplayTitle()}
            width={48}
            height={48}
            className="object-contain"
          />
        </div>

        <div className="flex min-w-0 flex-1 flex-col">
          <div className="txt-title-s text-txt-primary-normal">{getDisplayTitle()}</div>
          <div className="txt-label-s text-txt-secondary-normal">
            {formatTime(transaction.time)}
          </div>
        </div>
      </div>

      {/* 右侧：金额 */}
      <div className="flex items-center gap-2">
        <Image src="/icons/diamond.svg" alt="Diamond" width={16} height={16} />
        <div className="txt-numMonotype-l text-txt-primary-normal font-bold">
          +{formatFromCents(transaction.amount || 0)}
        </div>
      </div>
    </div>
  )
}

// 收入列表骨架屏组件
const IncomeItemSkeleton = () => (
  <div className="bg-surface-base-normal flex items-center justify-between rounded-lg p-6">
    <div className="flex flex-1 items-center gap-3">
      <div className="bg-surface-nest-normal h-16 w-16 animate-pulse rounded-lg"></div>
      <div className="flex flex-1 flex-col gap-2">
        <div className="bg-surface-nest-normal h-4 w-20 animate-pulse rounded"></div>
        <div className="bg-surface-nest-normal h-3 w-32 animate-pulse rounded"></div>
      </div>
    </div>
    <div className="flex items-center gap-2">
      <div className="bg-surface-nest-normal h-4 w-4 animate-pulse rounded"></div>
      <div className="bg-surface-nest-normal h-5 w-16 animate-pulse rounded"></div>
    </div>
  </div>
)

// 空状态组件
const IncomeEmptyState = () => (
  <div className="flex flex-col items-center justify-center py-12">
    <Empty title="No income record" />
  </div>
)

const IncomeList = () => {
  const { data } = useGetGiftList()
  const giftList = data?.datas || []

  // 获取收入类型的交易记录
  const {
    transactions,
    isLoading,
    isError,
    isFetchingNextPage,
    hasNextPage,
    fetchNextPage,
    refetch,
  } = useTransactionListWithInfiniteScroll({
    type: TransactionType.Income,
    pageSize: 20,
  })

  return (
    <div className="flex flex-col gap-4">
      <h2 className="txt-title-m text-txt-primary-normal">Earnings History</h2>

      <div className="bg-surface-base-normal w-full overflow-hidden rounded-lg p-6">
        <InfiniteScrollList<BillOutput>
          items={transactions}
          renderItem={(transaction) => <IncomeItem transaction={transaction} giftList={giftList} />}
          getItemKey={(transaction) => transaction.id?.toString() || 'unknown'}
          hasNextPage={!!hasNextPage}
          isLoading={isFetchingNextPage}
          fetchNextPage={fetchNextPage}
          columns={1}
          gap={6}
          className="!grid-cols-1"
          LoadingSkeleton={IncomeItemSkeleton}
          EmptyComponent={IncomeEmptyState}
          hasError={isError}
          onRetry={refetch}
          threshold={200}
          enabled={true}
        />
      </div>
    </div>
  )
}

export default IncomeList
