'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter, notFound } from 'next/navigation'
import { FiLock } from 'react-icons/fi'

import UserShell from '@/app/user/_components/UserShell'
import PageSkeleton from '@/app/user/_components/Skeletons/PageSkeleton'
import UserPageClient, { type ProfileTab } from './UserPageClient'
import type { UserBoardPostItem, UserPageData } from './_lib/loadUserPageData'

type LoaderState =
    | { status: 'loading' }
    | { status: 'blocked' }
    | { status: 'post_not_found' }
    | {
          status: 'ready'
          currentUserId: string | null
          currentUserAvatar: string | null
          data: UserPageData
          selectedPostId?: string
          selectedPost?: UserBoardPostItem
      }

function tabPathSuffix(tab: ProfileTab): string {
    if (tab === 'board') return '/posts'
    if (tab === 'replay') return '/replay'
    return ''
}

function buildProfileQuery(pathSuffix: string, postId: string): string {
    const params = new URLSearchParams()
    if (postId) {
        params.set('postId', postId)
    } else if (pathSuffix) {
        params.set('pathSuffix', pathSuffix)
    }
    const q = params.toString()
    return q ? `?${q}` : ''
}

function UserBlockedView() {
    return (
        <main className="flex-1 min-w-0 flex items-center justify-center px-4 sm:px-8 md:px-[120px]">
            <section className="w-full">
                <div className="mx-auto max-w-[800px] py-16 sm:py-20">
                    <BlockedMessage />
                </div>
            </section>
        </main>
    )
}

export default function UserPageLoader({ initialTab }: { initialTab: ProfileTab }) {
    const params = useParams()
    const router = useRouter()
    const userKey = String(params?.id ?? '').trim()
    const postId = String(params?.postId ?? '').trim()
    const [state, setState] = useState<LoaderState>({ status: 'loading' })

    useEffect(() => {
        if (!userKey) {
            router.replace('/')
            return
        }

        let cancelled = false
        const pathSuffix = postId ? '' : tabPathSuffix(initialTab)
        const query = buildProfileQuery(pathSuffix, postId)

        const load = async () => {
            setState({ status: 'loading' })
            try {
                const res = await fetch(`/api/users/${encodeURIComponent(userKey)}${query}`)
                const json = (await res.json()) as {
                    ok?: boolean
                    kind?: string
                    redirectTo?: string
                    currentUserId?: string | null
                    currentUserAvatar?: string | null
                    selectedPostId?: string
                    selectedPost?: UserBoardPostItem
                    data?: UserPageData
                }
                if (cancelled) return

                if (json.kind === 'redirect' && json.redirectTo) {
                    router.replace(json.redirectTo)
                    return
                }
                if (json.kind === 'post_not_found') {
                    setState({ status: 'post_not_found' })
                    return
                }
                if (!res.ok || json.kind === 'not_found') {
                    router.replace('/')
                    return
                }
                if (json.kind === 'blocked') {
                    setState({ status: 'blocked' })
                    return
                }
                if (json.kind === 'ok' && json.data) {
                    setState({
                        status: 'ready',
                        currentUserId: json.currentUserId ?? null,
                        currentUserAvatar: json.currentUserAvatar ?? null,
                        selectedPostId: json.selectedPostId,
                        selectedPost: json.selectedPost,
                        data: json.data,
                    })
                    return
                }
                router.replace('/')
            } catch {
                if (!cancelled) router.replace('/')
            }
        }

        void load()
        return () => {
            cancelled = true
        }
    }, [userKey, postId, initialTab, router])

    if (state.status === 'post_not_found') {
        notFound()
    }

    if (state.status === 'loading') {
        return (
            <UserShell initialUserInfo={null}>
                <PageSkeleton />
            </UserShell>
        )
    }

    if (state.status === 'blocked') {
        return (
            <UserShell initialUserInfo={null}>
                <UserBlockedView />
            </UserShell>
        )
    }

    const { data, currentUserId, currentUserAvatar, selectedPostId, selectedPost } = state
    return (
        <UserShell initialUserInfo={null}>
            <UserPageClient
                initialProfile={data.profile}
                initialVods={data.vodList}
                initialBoardPosts={data.boardPosts}
                currentUserId={currentUserId}
                initialIsFollowing={data.initialIsFollowing}
                initialIsBlocked={data.initialIsBlocked}
                initialIsBlockedByTarget={data.initialIsBlockedByTarget}
                initialSelectedPostId={selectedPostId ?? null}
                initialSelectedPost={selectedPost ?? null}
                initialCurrentUserAvatar={currentUserAvatar}
                initialTab={initialTab}
                initialGroups={data.groups}
            />
        </UserShell>
    )
}

function BlockedMessage() {
    return (
        <div className="flex flex-col items-center text-center gap-4">
            <div className="w-16 h-16 rounded-full bg-gray-100 dark:bg-neutral-900 flex items-center justify-center">
                <FiLock className="w-8 h-8 text-gray-500 dark:text-gray-400" />
            </div>
            <h2 className="text-lg sm:text-xl font-semibold text-gray-900 dark:text-gray-50">
                目前無法查看此個人頁面
            </h2>
        </div>
    )
}
