'use client'

import { useEffect, useRef, useState, useMemo } from 'react'
import Container from './Container'
import { parseChatWsMessageLoose } from '@/lib/chat/wsChat'
import { buildChatWsUrl, sendChatJoin } from '@/lib/chat/wsChat'
import { popoutChatFontSizePx } from '@/lib/chat/chatFontLevel'
import type { ChatSettingsView } from '@/lib/chat/chatSettingsView'
import { filterVisibleChatMessages } from '@/lib/chat/filterVisibleChatMessages'
import MessageList from './MessageList'
import InputArea from './InputArea'
import MessagesOverlay from './MessagesOverlay'
import ViewerCard from './ViewerCard'
import ParticipantsPopoverViewerCard from './ParticipantsPopoverViewerCard'
import SettingsPanel from './SettingsPanel'
import AdminPanel from './AdminPanel'
import type { ChatMessage, ParticipantItem, ParticipantSection, ViewerCardState, UserAdminInfo } from '../types'
import { CHAT_EMOJI_ITEMS } from './chatEmojis'

interface ChatPopoutWindowProps {
    roomId: string
    streamUserId: string
    currentUserId?: string | null
    currentUserDisplayName?: string | null
    isSuperAdmin: boolean
    isModerator: boolean
    isStreamer: boolean
    onClose: () => void
    onRestore: () => void
    t: (key: string) => string
}

export default function ChatPopoutWindow({
    roomId,
    streamUserId,
    currentUserId,
    currentUserDisplayName,
    isSuperAdmin,
    isModerator,
    isStreamer,
    onClose,
    onRestore,
    t,
}: ChatPopoutWindowProps) {
    // Refs
    const chatCardRef = useRef<HTMLDivElement>(null)
    const chatMessagesRef = useRef<HTMLDivElement>(null)
    const chatInputBarRef = useRef<HTMLDivElement>(null)
    const chatWriteAreaRef = useRef<HTMLDivElement>(null)
    const participantsBtnRef = useRef<HTMLButtonElement>(null)
    const settingsBtnRef = useRef<HTMLButtonElement>(null)
    const adminBtnRef = useRef<HTMLButtonElement>(null)
    const participantsRef = useRef<HTMLDivElement>(null)
    const settingsRef = useRef<HTMLDivElement>(null)
    const adminRef = useRef<HTMLDivElement>(null)
    const emojiBtnRef = useRef<HTMLButtonElement>(null)
    const emojiPanelRef = useRef<HTMLDivElement>(null)
    const chatViewerCardRef = useRef<HTMLDivElement>(null)
    const viewerCardRef = useRef<HTMLDivElement>(null)
    const mentionMessageRefs = useRef<Map<string, HTMLDivElement>>(new Map())

    // WebSocket
    const wsRef = useRef<WebSocket | null>(null)

    // States
    const [messages, setMessages] = useState<ChatMessage[]>([])
    const [chatDraft, setChatDraft] = useState('')
    const [participantsOpen, setParticipantsOpen] = useState(false)
    const [settingsOpen, setSettingsOpen] = useState(false)
    const [adminOpen, setAdminOpen] = useState(false)
    const [emojiOpen, setEmojiOpen] = useState(false)
    const [emojiMode, setEmojiMode] = useState<'desktop' | 'mobile'>('desktop')
    const [emojiTab, setEmojiTab] = useState<'recent' | 'subscription' | 'default'>('default')
    const [emojiClosing, setEmojiClosing] = useState(false)
    const [emojiEntering, setEmojiEntering] = useState(false)
    const [participantsClosing, setParticipantsClosing] = useState(false)
    const [participantsEntering, setParticipantsEntering] = useState(false)
    const [settingsClosing, setSettingsClosing] = useState(false)
    const [settingsEntering, setSettingsEntering] = useState(false)
    const [adminClosing, setAdminClosing] = useState(false)
    const [adminEntering, setAdminEntering] = useState(false)
    const [settingsView, setSettingsView] = useState<ChatSettingsView>('root')
    const [chatFontLevel, setChatFontLevel] = useState(4)
    const [emojiShow, setEmojiShow] = useState(true)
    const [highlightMentions, setHighlightMentions] = useState(true)
    const [hideSystemMessages, setHideSystemMessages] = useState(false)
    const [showGiftMessages, setShowGiftMessages] = useState(true)
    const [chatDisabled, setChatDisabled] = useState(false)
    const [isAtBottom, setIsAtBottom] = useState(true)
    const [unreadMentionMessages, setUnreadMentionMessages] = useState<Set<string>>(new Set())
    const [viewerCard, setViewerCard] = useState<ViewerCardState | null>(null)
    const [chatViewerCard, setChatViewerCard] = useState<ViewerCardState | null>(null)
    const [viewerCardDepth, setViewerCardDepth] = useState<'root' | 'gift' | 'admin'>('root')
    const [viewerCardBanStatus, setViewerCardBanStatus] = useState<{ userId: string; isBanned: boolean } | null>(null)
    const [userAdminInfo, setUserAdminInfo] = useState<UserAdminInfo | null>(null)
    const [participantSections, setParticipantSections] = useState<ParticipantSection[]>([])
    const [participantsMaxH, setParticipantsMaxH] = useState<number | null>(null)
    const [participantsShiftX, setParticipantsShiftX] = useState(0)
    const [settingsMaxH, setSettingsMaxH] = useState<number | null>(null)
    const [adminMaxH, setAdminMaxH] = useState<number | null>(null)
    const [banModalOpen, setBanModalOpen] = useState(false)
    const [banClosing, setBanClosing] = useState(false)
    const [banEntering, setBanEntering] = useState(false)
    const [banTargetUser, setBanTargetUser] = useState<{ name: string; id: string } | null>(null)
    const banRef = useRef<HTMLDivElement>(null)

    // Emoji items
    const emojiDefaultItems = CHAT_EMOJI_ITEMS

    // Font sizes
    const chatFontSizePx = useMemo(() => popoutChatFontSizePx(chatFontLevel), [chatFontLevel])
    const chatLineHeightPx = useMemo(() => {
        return chatFontSizePx * 1.5
    }, [chatFontSizePx])
    const chatScrollPreviewMessage = useMemo(() => {
        const visible = filterVisibleChatMessages(messages, {
            hideSystemMessages,
            showGiftMessages,
            currentUserId,
        })
        return visible.slice(-1)[0] ?? null
    }, [messages, hideSystemMessages, showGiftMessages, currentUserId])

    // Tip classes
    const tipBelowOnlyClass = 'tip-below-only'
    const tipAboveOnlyClass = 'tip-above-only'

    // WebSocket connection
    useEffect(() => {
        if (typeof window === 'undefined') return
        let isUnmounting = false

        const connectWebSocket = () => {
            if (isUnmounting) return
            try {
                const wsUrl = buildChatWsUrl()
                console.log('[Popout] Connecting to WebSocket:', wsUrl)
                const ws = new WebSocket(wsUrl)
                wsRef.current = ws

                ws.onopen = () => {
                    console.log('[Popout] WebSocket connected')
                    sendChatJoin(ws, {
                        roomId,
                        userId: currentUserId,
                        author: currentUserDisplayName || t('common.guest'),
                    })
                }

                ws.onmessage = (event) => {
                    try {
                        const data = parseChatWsMessageLoose(event.data as string)
                        if (!data) return
                        // Handle WebSocket messages (similar to main window)
                        if (data.type === 'chat') {
                            setMessages((prev) => [...prev, data.message])
                        }
                        // Add other message handlers as needed
                    } catch (error) {
                        console.error('[Popout] Failed to parse WebSocket message:', error)
                    }
                }

                ws.onerror = (error) => {
                    console.error('[Popout] WebSocket error:', error)
                }

                ws.onclose = () => {
                    console.log('[Popout] WebSocket disconnected')
                    wsRef.current = null
                    if (!isUnmounting) {
                        // Reconnect logic if needed
                    }
                }
            } catch (error) {
                console.error('[Popout] Failed to connect WebSocket:', error)
            }
        }

        connectWebSocket()

        return () => {
            isUnmounting = true
            if (wsRef.current) {
                wsRef.current.onclose = null
                wsRef.current.onerror = null
                wsRef.current.onmessage = null
                wsRef.current.close()
                wsRef.current = null
            }
        }
    }, [roomId, currentUserId, currentUserDisplayName, t])

    // Handle window close
    useEffect(() => {
        const handleBeforeUnload = () => {
            onRestore()
        }
        window.addEventListener('beforeunload', handleBeforeUnload)
        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload)
        }
    }, [onRestore])

    // Placeholder handlers (simplified for now)
    const sendChat = () => {
        // Implementation similar to main window
    }

    const scrollToBottom = () => {
        if (chatMessagesRef.current) {
            chatMessagesRef.current.scrollTop = chatMessagesRef.current.scrollHeight
        }
    }

    const isMessageMentioningMe = (message: ChatMessage) => {
        if (!currentUserId) return false
        return message.mentions?.some((m) => m.userId === currentUserId) || false
    }

    const openChatViewerCard = (mode: 'desktop' | 'mobile', e: React.MouseEvent<HTMLButtonElement>, message: ChatMessage) => {
        // Implementation
    }

    const openMentionViewerCard = (mode: 'desktop' | 'mobile', e: React.MouseEvent<HTMLButtonElement>, user: ParticipantItem) => {
        // Implementation
    }

    const openViewerCard = (mode: 'desktop' | 'mobile', e: React.MouseEvent<HTMLButtonElement>, user: ParticipantItem) => {
        // Implementation
    }

    const handleBanClick = (user: ParticipantItem) => {
        // Implementation
    }

    const handleUnban = (user: ParticipantItem) => {
        // Implementation
    }

    const handleAddMod = (user: ParticipantItem) => {
        // Implementation
    }

    const handleRemoveMod = (user: ParticipantItem) => {
        // Implementation
    }

    const clearChat = () => {
        setMessages([])
    }

    const handleToggleChat = () => {
        setChatDisabled((prev) => !prev)
    }

    return (
        <div className="w-full h-screen flex flex-col bg-white dark:bg-[#0c0d0e]">
            <Container
                variant="desktop"
                theaterMode={false}
                t={t}
                chatCardRef={chatCardRef}
                chatMessagesRef={chatMessagesRef}
                chatInputBarRef={chatInputBarRef}
                chatWriteAreaRef={chatWriteAreaRef}
                participantsBtnRef={participantsBtnRef}
                settingsBtnRef={settingsBtnRef}
                adminBtnRef={adminBtnRef}
                participantsOpen={participantsOpen}
                settingsOpen={settingsOpen}
                adminOpen={adminOpen}
                isSuperAdmin={isSuperAdmin}
                onCloseChat={onClose}
                onParticipantsToggle={() => setParticipantsOpen((prev) => !prev)}
                onSettingsToggle={() => setSettingsOpen((prev) => !prev)}
                onAdminToggle={() => setAdminOpen((prev) => !prev)}
                participantsPopover={
                    participantsOpen ? (
                        <ParticipantsPopoverViewerCard
                            mode="desktop"
                            panelRef={participantsRef}
                            maxH={participantsMaxH}
                            shiftX={participantsShiftX}
                            t={t}
                            participantsClosing={participantsClosing}
                            participantsEntering={participantsEntering}
                            onClose={() => setParticipantsOpen(false)}
                            sections={participantSections}
                            onUserClick={(e, u) => openViewerCard('desktop', e, u)}
                            streamerId={streamUserId}
                            viewerCard={viewerCard}
                            viewerCardRef={viewerCardRef}
                            viewerCardDepth={viewerCardDepth}
                            viewerCardBanStatus={viewerCardBanStatus}
                            userAdminInfo={userAdminInfo}
                            onCloseViewerCard={() => {
                                setViewerCard(null)
                                setViewerCardBanStatus(null)
                                setUserAdminInfo(null)
                            }}
                            onBackToRoot={() => setViewerCardDepth('root')}
                            onGift={() => { }}
                            onBan={handleBanClick}
                            onUnban={handleUnban}
                            onAddMod={handleAddMod}
                            onRemoveMod={handleRemoveMod}
                            isModerator={isModerator}
                            isStreamer={isStreamer}
                            isSuperAdmin={isSuperAdmin}
                            currentUserId={currentUserId}
                        />
                    ) : undefined
                }
                settingsPanel={
                    settingsOpen ? (
                        <SettingsPanel
                            panelRef={settingsRef}
                            maxH={settingsMaxH}
                            t={t}
                            settingsClosing={settingsClosing}
                            settingsEntering={settingsEntering}
                            settingsView={settingsView}
                            setSettingsView={setSettingsView}
                            closeSettings={() => setSettingsOpen(false)}
                            clearChat={clearChat}
                            popoutChat={() => { }}
                            chatFontLevel={chatFontLevel}
                            setChatFontLevel={setChatFontLevel}
                            chatFontSizePx={chatFontSizePx}
                            chatLineHeightPx={chatLineHeightPx}
                            emojiShow={emojiShow}
                            setEmojiShow={setEmojiShow}
                            highlightMentions={highlightMentions}
                            setHighlightMentions={setHighlightMentions}
                            hideSystemMessages={hideSystemMessages}
                            setHideSystemMessages={setHideSystemMessages}
                            showGiftMessages={showGiftMessages}
                            setShowGiftMessages={setShowGiftMessages}
                        />
                    ) : undefined
                }
                adminPanel={
                    adminOpen ? (
                        <AdminPanel
                            panelRef={adminRef}
                            maxH={adminMaxH}
                            t={t}
                            adminClosing={adminClosing}
                            adminEntering={adminEntering}
                            chatDisabled={chatDisabled}
                            onToggleChat={handleToggleChat}
                            onClose={() => setAdminOpen(false)}
                        />
                    ) : undefined
                }
                chatFontSizePx={chatFontSizePx}
                chatLineHeightPx={chatLineHeightPx}
                tipBelowOnlyClass={tipBelowOnlyClass}
                messagesContent={
                    <MessageList
                        messages={messages}
                        mode="desktop"
                        streamerId={streamUserId}
                        currentUserId={currentUserId}
                        mentionMessageRefs={mentionMessageRefs}
                        isMessageMentioningMe={isMessageMentioningMe}
                        openChatViewerCard={openChatViewerCard}
                        openMentionViewerCard={openMentionViewerCard}
                        hideSystemMessages={hideSystemMessages}
                        showGiftMessages={showGiftMessages}
                        t={t}
                    />
                }
                messagesOverlay={
                    <MessagesOverlay
                        mode="desktop"
                        isAtBottom={isAtBottom}
                        latestMessage={chatScrollPreviewMessage}
                        onScrollToBottom={scrollToBottom}
                        streamerId={streamUserId}
                        unreadMentionCount={unreadMentionMessages.size}
                        onScrollToMention={() => { }}
                        chatViewerCard={chatViewerCard}
                        chatViewerCardRef={chatViewerCardRef}
                        viewerCardDepth="root"
                        viewerCardBanStatus={viewerCardBanStatus}
                        bannedUserIds={new Set<string>()}
                        userAdminInfo={userAdminInfo}
                        onCloseViewerCard={() => {
                            setChatViewerCard(null)
                            setViewerCardBanStatus(null)
                        }}
                        onBackToRoot={() => { }}
                        onGift={() => { }}
                        onBan={handleBanClick}
                        onUnban={handleUnban}
                        onAddMod={handleAddMod}
                        onRemoveMod={handleRemoveMod}
                        isModerator={isModerator}
                        isStreamer={isStreamer}
                        isSuperAdmin={isSuperAdmin}
                        currentUserId={currentUserId}
                        t={t}
                    />
                }
                floatingOverlay={
                    viewerCard?.mode === 'desktop' && viewerCard ? (
                        <ViewerCard
                            cardRef={viewerCardRef}
                            viewerCard={viewerCard}
                            viewerCardDepth={viewerCardDepth}
                            t={t}
                            onClose={() => {
                                setViewerCard(null)
                                setViewerCardBanStatus(null)
                                setUserAdminInfo(null)
                            }}
                            onBackToRoot={() => setViewerCardDepth('root')}
                            onGift={() => {}}
                            onBan={handleBanClick}
                            onUnban={handleUnban}
                            isBanned={viewerCardBanStatus?.userId === viewerCard.user.id && viewerCardBanStatus.isBanned}
                            currentUserId={currentUserId}
                            userAdminInfo={userAdminInfo}
                            onAddMod={handleAddMod}
                            onRemoveMod={handleRemoveMod}
                            isModerator={isModerator}
                            isStreamer={isStreamer}
                            isSuperAdmin={isSuperAdmin}
                            streamerId={streamUserId}
                        />
                    ) : undefined
                }
                inputContent={
                    <InputArea
                        variant="desktop"
                        chatWriteAreaRef={chatWriteAreaRef}
                        emojiBtnRef={emojiBtnRef}
                        emojiPanelRef={emojiPanelRef}
                        chatCardRef={chatCardRef}
                        chatInputBarRef={chatInputBarRef}
                        draft={chatDraft}
                        setDraft={setChatDraft}
                        emojiOpen={emojiOpen}
                        emojiMode={emojiMode}
                        emojiTab={emojiTab}
                        setEmojiTab={setEmojiTab}
                        emojiDefaultItems={emojiDefaultItems}
                        emojiClosing={emojiClosing}
                        emojiEntering={emojiEntering}
                        onSend={sendChat}
                        onEmojiToggle={() => {
                            if (emojiOpen) {
                                setEmojiClosing(true)
                                setTimeout(() => {
                                    setEmojiOpen(false)
                                    setEmojiClosing(false)
                                }, 200)
                            } else {
                                setEmojiOpen(true)
                                setEmojiMode('desktop')
                                setEmojiEntering(true)
                                setTimeout(() => setEmojiEntering(false), 200)
                            }
                        }}
                        onEmojiClose={() => {
                            setEmojiClosing(true)
                            setTimeout(() => {
                                setEmojiOpen(false)
                                setEmojiClosing(false)
                            }, 200)
                        }}
                        onGiftClick={() => { }}
                        placeholder={currentUserId ? t('room.chatPlaceholder') : t('room.loginRequired')}
                        disabled={!currentUserId}
                        mentionUsers={[]}
                        chatDisabled={chatDisabled}
                        isSuperAdmin={isSuperAdmin}
                        tipAboveOnlyClass={tipAboveOnlyClass}
                        t={t}
                        showGiftButton={!!currentUserId && !isStreamer}
                    />
                }
            />
        </div>
    )
}

