import { route } from 'preact-router'
import { isAdministrator, Solution as SolutionModel, SolutionStat, SolutionStatMap, User } from '../../shared/model'
import { sortByStringKey } from '../../shared/utils'
import { prependBaseUrl } from '../../shared/utils'
import { Header } from '../components/Header'
import { Solution } from '../components/Solution'
import { useResource } from '../hooks'
import { useLoggedInUser } from '../hooks/useCurrentUser'

type RouteProps = {
    uid: string
}

export const UserPage = ({ uid }: RouteProps) => {
    // ottengo l'utente loggato, se è un admin le soluzioni devono mostrare i controlli speciali per admin
    const [currentUser] = useLoggedInUser()

    // ottengo le info sull'utente di questa pagina
    const [user] = useResource<null | User>(`/api/user/${uid}`, null, user => {
        if (!user) {
            route(prependBaseUrl(`/error?message=${encodeURIComponent(`Non c'è ancora nessun utente con username "${uid}"`)}`), true)
        }
    })

    // ottengo gli stat per l'utente di questa pagina
    const [stats] = useResource<null | SolutionStatMap>(`/api/stats`, null)
    if (!stats) {
        return <></>
    }

    const userStats = stats[uid]

    // ottengo le soluzioni pubbliche dell'utente di questa pagina
    const [solutions, refreshSolutions] = useResource<SolutionModel[]>(`/api/solutions?user=${uid}&public`, [])
    const sortedSolutions = sortByStringKey(solutions, s => s.createdAt, false)

    return (
        <>
            <Header />
            <main class="page-profile">
                <div class="title">
                    Profilo di <a href={prependBaseUrl(`/u/${uid}`)}>{user?.fullName}</a>
                </div>
                <hr />
                <div class="subtitle">Statistiche</div>
                <div class="info">
                    <div>Soluzioni inviate</div>
                    <div>Soluzioni corrette</div>
                    <div class="info-box">{userStats?.sentSolutionsCount ?? 0}</div>
                    <div class="info-box">{userStats?.correctSolutionsCount ?? 0}</div>
                </div>
                <hr />
                <div class="subtitle">Soluzioni notevoli</div>
                <div class="solution-list">
                    {sortedSolutions.map(solution => (
                        <Solution
                            refreshSolution={refreshSolutions}
                            {...solution}
                            adminControls={currentUser !== null && isAdministrator(currentUser.role)}
                        />
                    ))}
                </div>
            </main>
        </>
    )
}
