'use client'

import Image from 'next/image'
import { FiUser } from 'react-icons/fi'
import { formatGiftCoinAmount, getGiftSuperChatTier } from '@/lib/gifts/giftSuperChat'
import { getGiftSuperChatTheme } from '@/lib/gifts/giftSuperChatTheme'
import { resolveMediaUrl } from '@/lib/media/resolveMediaUrl'
import { hasValidImageSrc } from '@/lib/media/mediaGuards'
import { getGiftCardUserNameClass, getUserRoleBadge } from './UserRoleUtils'
import type { ChatMessage, ParticipantItem } from '../types'

const COIN_IMAGE = '/images/room/coin.png'

function GiftAvatar({
    src,
    alt,
    zIndexClass,
    sizeClass = 'h-6 w-6',
    onClick,
}: {
    src?: string | null
    alt: string
    zIndexClass: string
    sizeClass?: string
    onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void
}) {
    const resolved = resolveMediaUrl(src)
    const showImage = hasValidImageSrc(resolved)

    const inner = showImage ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img
            src={resolved}
            alt=""
            className="h-full w-full object-cover select-none"
            loading="lazy"
            decoding="async"
            draggable={false}
        />
    ) : (
        <FiUser className="h-3.5 w-3.5 text-gray-400 dark:text-gray-500" aria-hidden />
    )

    const className = `relative flex ${sizeClass} shrink-0 items-center justify-center overflow-hidden rounded-full border border-black/5 bg-[#f7f7f7] dark:border-white/10 dark:bg-neutral-800 ${zIndexClass}`

    if (onClick) {
        return (
            <button type="button" onClick={onClick} className={className} aria-label={alt}>
                {inner}
            </button>
        )
    }

    return (
        <span className={className} aria-hidden>
            {inner}
        </span>
    )
}

function resolveGiftRecipientUserType(
    recipientUserId: string,
    streamerId?: string,
    modUserIds?: ReadonlySet<string>,
    superAdminUserIds?: ReadonlySet<string>
): ParticipantItem['userType'] | undefined {
    if (streamerId && recipientUserId === streamerId) return 'streamer'
    if (superAdminUserIds?.has(recipientUserId)) return 'superAdmin'
    if (modUserIds?.has(recipientUserId)) return 'manager'
    return undefined
}

type GiftChatMessageProps = {
    message: ChatMessage
    streamerId?: string
    getUserAvatar?: (userId: string | null | undefined) => string | null | undefined
    openChatViewerCard?: (
        mode: 'desktop' | 'mobile',
        e: React.MouseEvent<HTMLButtonElement>,
        message: ChatMessage
    ) => void
    openMentionViewerCard?: (
        mode: 'desktop' | 'mobile',
        e: React.MouseEvent<HTMLButtonElement>,
        user: ParticipantItem
    ) => void
    mode: 'desktop' | 'mobile'
    t: (key: string, params?: Record<string, string>) => string
    className?: string
    modUserIds?: ReadonlySet<string>
    superAdminUserIds?: ReadonlySet<string>
    /** 置頂訊息等不在聊天捲動區時，需明確套用聊天字級 */
    chatFontSizePx?: number
    chatLineHeightPx?: number
}

function GiftSuperChatMessage({
    message,
    streamerId,
    getUserAvatar,
    openChatViewerCard,
    openMentionViewerCard,
    mode,
    t,
    className = '',
    modUserIds,
    superAdminUserIds,
    chatFontSizePx,
    chatLineHeightPx,
}: GiftChatMessageProps) {
    const gift = message.gift!
    const tier = getGiftSuperChatTier(gift.totalPrice)
    const theme = getGiftSuperChatTheme(tier)
    const senderName = message.author?.trim() || t('common.guest')
    const recipientName =
        gift.recipientName?.trim() || gift.recipientDisplayId?.trim() || gift.recipientUserId

    const recipientItem: ParticipantItem = {
        role: '',
        id: gift.recipientUserId,
        name: recipientName,
        userType: resolveGiftRecipientUserType(
            gift.recipientUserId,
            streamerId,
            modUserIds,
            superAdminUserIds
        ),
        profileApiKey: gift.recipientDisplayId,
    }

    const senderBadge = getUserRoleBadge(message, streamerId, modUserIds, superAdminUserIds)
    const recipientBadge = getUserRoleBadge(recipientItem, streamerId, modUserIds, superAdminUserIds)
    const senderAvatar = getUserAvatar?.(message.userId)
    const recipientAvatar = getUserAvatar?.(gift.recipientUserId)
    const countSuffix = `×${Math.max(1, Math.floor(gift.count) || 1)}`

    const senderHeaderNameClass = getGiftCardUserNameClass(
        message,
        streamerId,
        openChatViewerCard ? theme.headerNameButton : theme.headerName,
        'header',
        modUserIds,
        superAdminUserIds,
    )
    const recipientBodyNameClass = getGiftCardUserNameClass(
        recipientItem,
        streamerId,
        openMentionViewerCard ? theme.bodyNameButton : theme.bodyName,
        'body',
        modUserIds,
        superAdminUserIds,
    )

    const chatFontStyle =
        typeof chatFontSizePx === 'number'
            ? {
                  fontSize: `${chatFontSizePx}px`,
                  lineHeight: chatLineHeightPx ? `${chatLineHeightPx}px` : undefined,
              }
            : undefined

    return (
        <div className={`flex w-full py-1 ${className}`} style={chatFontStyle}>
            <div
                className={`${theme.card} select-none`}
                role="article"
                aria-label={t('room.giftMessage.superChatAria', {
                    amount: formatGiftCoinAmount(gift.totalPrice),
                    sender: senderName,
                })}
            >
                <div className={theme.header}>
                    <div className="flex shrink-0 items-center">
                        <GiftAvatar
                            src={senderAvatar}
                            alt={senderName}
                            zIndexClass="z-[1]"
                            sizeClass="h-[2.25em] w-[2.25em]"
                            onClick={
                                openChatViewerCard
                                    ? (e) => openChatViewerCard(mode, e, message)
                                    : undefined
                            }
                        />
                        <GiftAvatar
                            src={recipientAvatar}
                            alt={recipientName}
                            zIndexClass="-ml-2.5 z-0"
                            sizeClass="h-[2.25em] w-[2.25em]"
                            onClick={
                                openMentionViewerCard
                                    ? (e) => openMentionViewerCard(mode, e, recipientItem)
                                    : undefined
                            }
                        />
                    </div>
                    <div className="min-w-0 flex-1">
                        <div className="flex min-w-0 flex-wrap items-center gap-x-1">
                            {senderBadge}
                            {openChatViewerCard ? (
                                <button
                                    type="button"
                                    onClick={(e) => openChatViewerCard(mode, e, message)}
                                    className={senderHeaderNameClass}
                                >
                                    {senderName}
                                </button>
                            ) : (
                                <span className={senderHeaderNameClass}>{senderName}</span>
                            )}
                        </div>
                        <div className={theme.headerAmount}>
                            <Image
                                src={COIN_IMAGE}
                                alt=""
                                width={16}
                                height={16}
                                className="h-[1.15em] w-[1.15em] shrink-0 object-contain select-none"
                                draggable={false}
                                unoptimized
                                aria-hidden
                            />
                            {formatGiftCoinAmount(gift.totalPrice)}
                        </div>
                    </div>
                    <span className={theme.count}>{countSuffix}</span>
                </div>

                <div className={theme.body}>
                    <div className="min-w-0 flex-1 flex flex-wrap items-center gap-x-1 gap-y-1 leading-snug">
                        <span className={theme.bodyMuted}>{t('room.giftMessage.to')}</span>
                        <span className="inline-flex items-center whitespace-nowrap">
                            {recipientBadge}
                            {openMentionViewerCard ? (
                                <button
                                    type="button"
                                    onClick={(e) => openMentionViewerCard(mode, e, recipientItem)}
                                    className={recipientBodyNameClass}
                                >
                                    {recipientName}
                                </button>
                            ) : (
                                <span className={recipientBodyNameClass}>{recipientName}</span>
                            )}
                        </span>
                        <span className={theme.bodyMuted}>{t('room.giftMessage.sent')}</span>
                    </div>
                    {gift.image ? (
                        <div className="flex shrink-0 items-center justify-end">
                            <Image
                                src={gift.image}
                                alt=""
                                width={36}
                                height={36}
                                className="h-[4em] w-auto object-contain select-none"
                                draggable={false}
                                unoptimized
                            />
                        </div>
                    ) : null}
                </div>
            </div>
        </div>
    )
}

export default function GiftChatMessage(props: GiftChatMessageProps) {
    if (!props.message.gift) return null

    return <GiftSuperChatMessage {...props} />
}
