import { route } from 'preact-router'
import { useState } from 'preact/hooks'
import { isAdministrator, isStudent, Solution as SolutionModel, SolutionId } from '../../shared/model'
import { sortByStringKey } from '../../shared/utils'
import { prependBaseUrl, server } from '../api'
import { Header } from '../components/Header'
import { MarkdownEditor } from '../components/MarkdownEditor'
import { Select } from '../components/Select'
import { Solution } from '../components/Solution'
import { useCurrentUser, useListResource, useResource } from '../hooks'

const CreateProblem = ({}) => {
    const [source, setSource] = useState('')
    const createProblem = async () => {
        const id = await server.post('/api/problem', {
            content: source,
        })

        route(prependBaseUrl(`/problem/${id}`))
    }

    return (
        <>
            <MarkdownEditor {...{ source, setSource }} />
            <button onClick={createProblem}>Aggiungi Problema</button>
        </>
    )
}

type SortOrder = 'latest' | 'oldest'

export const AdminPage = ({}) => {
    const [user] = useCurrentUser(user => {
        if (!user) {
            route(prependBaseUrl('/login'), true)
        } else if (isStudent(user.role)) {
            route(prependBaseUrl('/'), true)
        }
    })

    const [solutions, refreshSolutions, setSolutionHeuristic] =
        useListResource<SolutionModel>(`/api/solutions`)

    const [sortOrder, setSortOrder] = useState<SortOrder>('oldest')

    const sortedSolutions = sortByStringKey(solutions, s => s.createdAt, sortOrder === 'oldest')

    const [trackInteracted, setTrackedInteracted] = useState<Set<SolutionId>>(new Set())

    const hasUntrackedPending =
        sortedSolutions.filter(s => s.status === 'pending' || trackInteracted.has(s.id)).length > 0

    return (
        user && (
            <main class="page-admin">
                <Header {...{ user }} />
                <div class="subtitle">Nuovo problema</div>
                <CreateProblem />
                <div class="subtitle">Soluzioni da correggere</div>
                {hasUntrackedPending ? (
                    <div class="solution-list">
                        <div class="controls">
                            <div class="sort-order">
                                <Select
                                    value={sortOrder}
                                    setValue={setSortOrder}
                                    options={{
                                        latest: 'Prima più recenti',
                                        oldest: 'Prima più antichi',
                                    }}
                                />
                            </div>
                        </div>
                        {sortedSolutions.map(
                            (s, index) =>
                                (s.status === 'pending' || trackInteracted.has(s.id)) && (
                                    <Solution
                                        adminControls
                                        {...s}
                                        setSolution={solFn => {
                                            setTrackedInteracted(prev => new Set([...prev, s.id]))
                                            setSolutionHeuristic(index, solFn)
                                        }}
                                        refreshSolution={refreshSolutions}
                                    />
                                )
                        )}
                    </div>
                ) : (
                    <>
                        <em>Nessuna soluzione ancora da correggere</em>
                    </>
                )}
            </main>
        )
    )
}
