import { redirect } from 'next/navigation'
import { getDb } from '@/server/db'
import { fetchUserActiveAvatarFrame } from '@/server/avatarFrames/query'
import { USER_AUTH_SQL } from '@/server/userAuthSql'
import { resolveRoomRouteParam } from '@/server/roomRoute'
import { cookies } from 'next/headers'
import { SESSION_ID_COOKIE } from '@/app/_helpers/constants'
import { pickRowNumber, pickRowString, readDisplayName } from '@/server/pgRow'
import { isStreamLiveByLifecycleStatus } from '@/lib/streams/lifecycleStatus'
import { roomStreamCategoryToTagIds } from '@/lib/streams/roomStreamCategory'
import RoomPageClientMb from '@/app/mb/room/[id]/RoomPageClientMb'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

type DbUserRow = {
    id: string
    displayName: string
    avatar: string | null
    followersCount: number
    isVerified: number
    vipLevel: string
}

type DbStreamRow = {
    roomId: string
    userId: string
    streamStatus: string | null
    title: string
    likes: number
    startedAt: string | number | null
    category: string | null
    thumbnail: string | null
    src: string | null
}

type DbIsLikedRow = { c: number }
type DbIsFollowingRow = { c: number }
function safeParseJsonArray(input: unknown): string[] {
    if (!input || typeof input !== 'string') return []
    try {
        const v = JSON.parse(input)
        if (Array.isArray(v)) return v.map((x) => String(x))
        return []
    } catch {
        return []
    }
}

export default async function MbRoomIdPage({ params }: { params: { id: string } }) {
    const routeParam = String(params?.id ?? '').trim()
    const db = await getDb()
    const resolvedRoom = await resolveRoomRouteParam(db, routeParam)

    if (!resolvedRoom) {
        redirect('/')
    }
    if (resolvedRoom.shouldRedirect) {
        redirect(`/mb/room/${resolvedRoom.publicRoomId}`)
    }

    const roomId = resolvedRoom.roomId

    const streamRow = await db.get<DbStreamRow>(
        `SELECT 
            rs.room_id AS roomId,
            rs.room_id AS userId,
            rs.stream_status AS streamStatus,
            rs.title,
            (SELECT COUNT(1) FROM room_stream_likes l WHERE l.room_id = rs.room_id) AS likes,
            rs.started_at AS startedAt,
            rs.category,
            rs.thumbnail_url AS thumbnail,
            rs.stream_token AS src
         FROM room_streams rs WHERE rs.room_id = ?`,
        [roomId]
    )

    const likesFromReactions = Number(streamRow?.likes ?? 0)

    const userId = pickRowString(streamRow as Record<string, unknown> | undefined, 'userId', 'user_id') || roomId
    const user = await db.get<DbUserRow>(
        `SELECT u.user_id AS id, u.display_name AS displayName, u.avatar_url AS avatar,
                (SELECT COUNT(1) FROM user_actions f WHERE f.target_id = u.user_id AND f.action_type = 'follow') AS followersCount,
                u.is_verified AS isVerified, 'none' AS vipLevel
         FROM users u WHERE u.user_id = ?`,
        [userId]
    )

    if (!readDisplayName(user as Record<string, unknown>)) {
        redirect('/')
    }

    const avatarFrame = await fetchUserActiveAvatarFrame(db, userId)

    const fallbackSrc = 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'
    const streamSrc = (streamRow?.src ?? '').trim()
    const isLive = isStreamLiveByLifecycleStatus(streamRow?.streamStatus)
    const playbackSrc = streamSrc || fallbackSrc

    let currentUserId: string | null = null
    let currentUserDisplayName: string | null = null
    let currentUserAvatar: string | null = null
    try {
        const sessionId = cookies().get(SESSION_ID_COOKIE)?.value
        if (sessionId) {
            const session = await db.get<Record<string, unknown>>(
                USER_AUTH_SQL.selectSessionUserId,
                [sessionId]
            )
            const sessionUserId = pickRowString(session, 'userId', 'user_id')
            if (sessionUserId) {
                currentUserId = sessionUserId
                const currentUser = await db.get<Record<string, unknown>>(
                    `SELECT display_name AS displayName, avatar_url AS avatar FROM users WHERE user_id = ?`,
                    [sessionUserId]
                )
                if (currentUser) {
                    currentUserDisplayName = readDisplayName(currentUser)
                    currentUserAvatar = pickRowString(currentUser, 'avatar', 'avatar_url') || null
                }
            }
        }
    } catch (error) {
        console.error('Failed to get current user ID:', error)
    }

    const initialIsLiked = currentUserId
        ? Boolean(
            (await db.get<DbIsLikedRow>(
                `SELECT 1 as c FROM room_stream_likes WHERE room_id = ? AND user_id = ? LIMIT 1`,
                [roomId, currentUserId]
            ))?.c
        )
        : false

    const initialIsFollowing = currentUserId
        ? Boolean(
            (await db.get<DbIsFollowingRow>(
                `SELECT 1 AS c FROM user_actions WHERE user_id = ? AND target_id = ? AND action_type = 'follow' LIMIT 1`,
                [currentUserId, userId]
            ))?.c
        )
        : false

    const row = user as Record<string, unknown>
    const rawVip = (row.vipLevel ?? row.viplevel ?? 'none').toString().trim().toLowerCase()
    const vipLevel: 'none' | 'vip' | 'vvip' | 'svip' | 'royal' =
        rawVip === 'vip' || rawVip === 'vvip' || rawVip === 'svip' || rawVip === 'royal'
            ? (rawVip as 'vip' | 'vvip' | 'svip' | 'royal')
            : 'none'

    if (process.env.NODE_ENV === 'development') {
        console.log('[mb room] streamer:', { userId, channelName: user?.displayName, rawVip, vipLevel, 'row.vipLevel': row.vipLevel })
    }

    const stream = {
        id: roomId,
        userId,
        title: streamRow?.title ?? '',
        channelName: readDisplayName(user as Record<string, unknown>),
        avatar: pickRowString(user as Record<string, unknown>, 'avatar', 'avatar_url'),
        viewers: 0,
        likes: likesFromReactions,
        followers: pickRowNumber(user as Record<string, unknown>, 'followersCount', 'followerscount'),
        startedAt: String(streamRow?.startedAt ?? '').trim(),
        tags: roomStreamCategoryToTagIds(streamRow?.category),
        isVerified: Boolean(user?.isVerified === 1),
        vipLevel,
        avatarFrame,
    }

    return (
        <RoomPageClientMb
            initialRoomId={roomId}
            initialRoomPublicId={resolvedRoom.publicRoomId}
            initialStream={stream}
            initialIsLiveStream={isLive}
            initialPlaybackSrc={playbackSrc}
            initialIsLiked={initialIsLiked}
            initialIsFollowing={initialIsFollowing}
            currentUserId={currentUserId}
            currentUserDisplayName={currentUserDisplayName}
            currentUserAvatar={currentUserAvatar}
        />
    )
}
