'use client'

import { useState } from 'react'
import { FiX, FiChevronDown, FiChevronUp } from 'react-icons/fi'
import { BiSolidPin } from 'react-icons/bi'
import { FaCrown, FaWrench } from 'react-icons/fa'
import { FaS } from 'react-icons/fa6'

// type
import type { ChatMessage, ParticipantItem } from '../types'

// utils
import { getUserRoleBadge, getUserNameColor } from './UserRoleUtils'

// components
import { renderMessageText } from './RenderMessageText'
import GiftChatMessage from './GiftChatMessage'

interface PinnedMessageProps {
    message: ChatMessage | null
    mode: 'desktop' | 'mobile'
    streamerId: string
    currentUserId?: string | null
    openChatViewerCard: (mode: 'desktop' | 'mobile', e: React.MouseEvent<HTMLButtonElement>, message: ChatMessage) => void
    openMentionViewerCard: (mode: 'desktop' | 'mobile', e: React.MouseEvent<HTMLButtonElement>, user: ParticipantItem) => void
    onUnpin?: () => void
    isModerator?: boolean
    emojiItems?: Array<{ id: string; alt: string; code: string; src: string }>
    getUserAvatar?: (userId: string | null | undefined) => string | null | undefined
    modUserIds?: ReadonlySet<string>
    superAdminUserIds?: ReadonlySet<string>
    t: (key: string, params?: Record<string, string>) => string
    chatFontSizePx?: number
    chatLineHeightPx?: number
    showGiftMessages?: boolean
}

function getRoleIcon(adminUserType?: 'streamer' | 'manager' | 'superAdmin'): React.ReactNode {
    const isStreamer = adminUserType === 'streamer'
    const isMod = adminUserType === 'manager'
    const isSuperAdmin = adminUserType === 'superAdmin'
    const roleIcon = isStreamer ? (
        <span className="inline-flex items-center justify-center w-4 h-4 rounded-sm bg-orange-500 border border-orange-600 dark:border-orange-400 flex-shrink-0">
            <FaCrown className="w-2.5 h-2.5 text-white" />
        </span>
    ) : isMod ? (
        <span className="inline-flex items-center justify-center w-4 h-4 rounded-sm bg-blue-500 border border-blue-600 dark:border-blue-400 flex-shrink-0">
            <FaWrench className="w-2.5 h-2.5 text-white" />
        </span>
    ) : isSuperAdmin ? (
        <span className="inline-flex items-center justify-center w-4 h-4 rounded-sm bg-purple-500 border border-purple-600 dark:border-purple-400 flex-shrink-0">
            <FaS className="w-2.5 h-2.5 text-white" />
        </span>
    ) : null
    return roleIcon
}

export default function PinnedMessage({
    message,
    mode,
    streamerId,
    currentUserId,
    openChatViewerCard,
    openMentionViewerCard,
    onUnpin,
    isModerator = false,
    emojiItems,
    getUserAvatar,
    modUserIds,
    superAdminUserIds,
    t,
    chatFontSizePx,
    chatLineHeightPx,
    showGiftMessages = true,
}: PinnedMessageProps) {
    const [isExpanded, setIsExpanded] = useState(false)

    if (!message) return null
    if (message.gift && !showGiftMessages) return null

    const pinnedBy = message.pinnedBy
    const roleIcon = pinnedBy ? getRoleIcon(pinnedBy.userType) : null

    return (
        <div className="absolute top-2 left-2 right-2 z-10">
            <div className="bg-white dark:bg-[#0c0d0e] rounded-lg border border-gray-200 dark:border-gray-700 shadow-md">
                <div className="px-3 py-2">
                    <div className="flex items-start gap-2">
                        <button
                            type="button"
                            onClick={() => setIsExpanded(!isExpanded)}
                            className="p-1 rounded hover:bg-gray-100 dark:hover:bg-[#1a1c21] transition-colors flex-shrink-0 mt-0.5"
                            aria-label={isExpanded ? t('room.message.collapse') : t('room.message.expand')}
                        >
                            {isExpanded ? (
                                <FiChevronUp className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                            ) : (
                                <FiChevronDown className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                            )}
                        </button>
                        <div className="flex-1 min-w-0">
                            <div className="text-xs text-gray-500 dark:text-gray-400 mb-1 flex items-center gap-1">
                                <BiSolidPin className="w-4 h-4 text-gray-500 dark:text-gray-400 flex-shrink-0" />
                                {pinnedBy ? (
                                    <>
                                        <span>{t('room.message.pinnedBy')}</span>
                                        {roleIcon}
                                        <span className="font-medium">{pinnedBy.author}</span>
                                        <span>{t('room.message.pinned')}</span>
                                    </>
                                ) : (
                                    <span className="font-medium">{t('room.message.pinned')}</span>
                                )}
                            </div>
                            <div
                                className={`transition-all duration-300 ${isExpanded ? '' : 'line-clamp-1'} ${
                                    message.gift ? '' : 'text-gray-900 dark:text-gray-100'
                                }`}
                            >
                                {message.gift ? (
                                    <GiftChatMessage
                                        message={message}
                                        streamerId={streamerId}
                                        getUserAvatar={getUserAvatar}
                                        openChatViewerCard={openChatViewerCard}
                                        openMentionViewerCard={openMentionViewerCard}
                                        mode={mode}
                                        t={t}
                                        className="pt-0"
                                        modUserIds={modUserIds}
                                        superAdminUserIds={superAdminUserIds}
                                        chatFontSizePx={chatFontSizePx}
                                        chatLineHeightPx={chatLineHeightPx}
                                    />
                                ) : isExpanded ? (
                                    <div className="flex items-center flex-wrap gap-1">
                                        {getUserRoleBadge(message, streamerId, modUserIds, superAdminUserIds)}
                                        <button
                                            type="button"
                                            onClick={(e) => {
                                                e.stopPropagation()
                                                openChatViewerCard(mode, e, message)
                                            }}
                                            className={`font-semibold  cursor-pointer ${getUserNameColor(message, streamerId, modUserIds, superAdminUserIds)}`}
                                        >
                                            {message.author}
                                        </button>
                                        {' '}
                                        {renderMessageText(message, openMentionViewerCard, mode, t, emojiItems, currentUserId, false, streamerId)}
                                    </div>
                                ) : (
                                    <div className="flex items-center gap-1 min-w-0">
                                        {getUserRoleBadge(message, streamerId, modUserIds, superAdminUserIds)}
                                        <button
                                            type="button"
                                            onClick={(e) => {
                                                e.stopPropagation()
                                                openChatViewerCard(mode, e, message)
                                            }}
                                            className={`font-semibold  cursor-pointer flex-shrink-0 ${getUserNameColor(message, streamerId, modUserIds, superAdminUserIds)}`}
                                        >
                                            {message.author}
                                        </button>
                                        <span className="truncate">
                                            {renderMessageText(message, openMentionViewerCard, mode, t, emojiItems, currentUserId, false, streamerId)}
                                        </span>
                                    </div>
                                )}
                            </div>
                        </div>
                        {isModerator && onUnpin && (
                            <button
                                type="button"
                                onClick={onUnpin}
                                className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors flex-shrink-0 mt-0.5"
                                aria-label={t('room.message.unpin')}
                            >
                                <FiX className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                            </button>
                        )}
                    </div>
                </div>
            </div>
        </div>
    )
}

