'use client'

import Image from 'next/image'
import { FiRefreshCcw, FiX } from 'react-icons/fi'
import { FaBan } from 'react-icons/fa'
import { FaUser } from 'react-icons/fa6'
import {
    formatParticipantPublicId,
    type ParticipantItem,
    type ParticipantSection,
} from '@/app/room/_components/types'
import { getUserRoleBadge, getUserNameColor } from '@/app/room/_components/chat/UserRoleUtils'
import { hasValidImageSrc } from '@/lib/media/mediaGuards'
import { resolveMediaUrl } from '@/lib/media/resolveMediaUrl'

function ParticipantAvatar({ avatarUrl, name }: { avatarUrl?: string; name: string }) {
    const src = resolveMediaUrl(avatarUrl)
    const showImage = hasValidImageSrc(src)

    return (
        <span className="relative flex h-5 w-5 flex-shrink-0 overflow-hidden rounded-full border border-gray-200 dark:border-gray-700">
            {showImage ? (
                <Image src={src} alt={name} width={20} height={20} className="h-full w-full object-cover" unoptimized />
            ) : (
                <span className="flex h-full w-full items-center justify-center rounded-full bg-gray-100 dark:bg-white/10">
                    <FaUser className="h-2.5 w-2.5 text-gray-400 dark:text-white/50" aria-hidden />
                </span>
            )}
        </span>
    )
}

export default function ParticipantsPopover({
    panelRef,
    maxH,
    shiftX,
    t,
    participantsClosing,
    participantsEntering,
    onClose,
    onRefresh,
    sections,
    onUserClick,
    streamerId,
    children,
}: {
    panelRef: React.RefObject<HTMLDivElement>
    maxH: number | null
    shiftX: number
    t: (key: string) => string
    participantsClosing: boolean
    participantsEntering: boolean
    onClose: () => void
    onRefresh?: () => void
    sections: ParticipantSection[]
    onUserClick: (e: React.MouseEvent<HTMLButtonElement>, u: ParticipantItem) => void
    streamerId?: string
    children?: React.ReactNode
}) {
    return (
        <div
            ref={panelRef}
            className={`absolute top-full right-0 mt-2 z-[120] w-[280px] max-w-[calc(100vw-24px)] rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-[#0c0d0e] shadow-lg overflow-visible flex flex-col origin-top-right transform-gpu transition-[opacity,transform] duration-200 ease-[cubic-bezier(0.56,0.12,0.12,0.98)] ${participantsClosing || participantsEntering ? 'opacity-0 scale-95 pointer-events-none' : 'opacity-100 scale-100'
                }`}
            style={{
                ...(maxH ? { maxHeight: `${maxH}px` } : null),
                translate: `${shiftX}px 0`,
            }}
        >
            <div className="flex items-center h-12 px-4 flex-shrink-0 rounded-t-xl overflow-hidden bg-white dark:bg-[#0c0d0e]">
                <h3 className="text-base font-semibold text-gray-900 dark:text-white">{t('room.participants.title')}</h3>
                <div className="ml-auto flex items-center gap-1">
                    <button
                        type="button"
                        aria-label={t('room.refresh')}
                        onClick={onRefresh}
                        className="w-8 h-8 rounded-lg inline-flex items-center justify-center hover:bg-gray-100 dark:hover:bg-[#1a1c21] transition-colors"
                    >
                        <FiRefreshCcw className="w-4.5 h-4.5 text-gray-600 dark:text-gray-300" />
                    </button>
                    <button
                        type="button"
                        aria-label={t('room.close')}
                        onClick={onClose}
                        className="w-8 h-8 rounded-full inline-flex items-center justify-center hover:bg-gray-100 dark:hover:bg-[#1a1c21] transition-colors"
                    >
                        <FiX className="w-5 h-5 text-gray-600 dark:text-gray-300" />
                    </button>
                </div>
            </div>

            <div className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden hide-scrollbar pb-3 rounded-b-xl bg-white dark:bg-[#0c0d0e]">
                {sections.map((section) => (
                    <div key={section.title}>
                        <div className="px-4 pt-3 pb-1 text-sm font-medium text-[#525661] dark:text-gray-300">
                            <span>{section.title}</span>{' '}
                            <span className="text-[#757b8a] dark:text-gray-400 font-semibold">({section.items.length})</span>
                        </div>
                        <div>
                            {section.items.map((u) => (
                                <button
                                    key={`${section.title}-${u.id}`}
                                    type="button"
                                    onClick={(e) => onUserClick(e, u)}
                                    className="w-full flex items-center gap-2 px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-[#1a1c21] transition-colors"
                                >
                                    <ParticipantAvatar avatarUrl={u.avatarUrl} name={u.name} />
                                    {getUserRoleBadge(u, streamerId)}
                                    <span className={`text-sm font-semibold flex-shrink-0 ${getUserNameColor(u, streamerId)}`}>
                                        {u.id.startsWith('guest_') ? t('room.participants.guestBadge') : u.name}
                                    </span>
                                    <span className="text-sm text-gray-500 dark:text-gray-400 truncate flex items-center gap-1">
                                        ({formatParticipantPublicId(u)})
                                        {u.isBanned && (
                                            <FaBan
                                                className="w-4 h-4 text-red-500 dark:text-red-400 flex-shrink-0"
                                                aria-label={t('room.participants.banned')}
                                            />
                                        )}
                                    </span>
                                </button>
                            ))}
                        </div>
                    </div>
                ))}
            </div>

            {children}
        </div>
    )
}


