import { route } from 'preact-router'
import { useState } from 'preact/hooks'
import { isAdministrator, 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 { useListResource } from '../hooks'
import { useCurrentUser } from '../hooks/useCurrentUser'

const CreateProblem = ({}) => {
    const [source, setSource] = useState('')

    type ProblemFields = {
        title?: string
        content: string
    }

    const createProblem = async () => {
        if (source.trim().length === 0) {
            alert('Il campo di testo è vuoto!')
            return
        }

        const id = await server.post<ProblemFields>('/api/problem', {
            content: source,
        })

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

    return (
        <>
            <MarkdownEditor placeholder="Scrivi un nuovo problema..." {...{ source, setSource }} />
            <button onClick={createProblem}>Aggiungi Problema</button>
        </>
    )
}

type SortOrder = 'latest' | 'oldest'

export const AdminPage = ({}) => {
    const [user, ready] = useCurrentUser()
    if (!ready) {
        return <></>
    }
    if (user === null) {
        route(prependBaseUrl('/login'), true)
        return <></>
    }
    if (!isAdministrator(user.role)) {
        route(prependBaseUrl('/'), true)
        return <></>
    }

    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 (
        <>
            <Header />
            <main class="page-admin">
                <div class="subtitle">Nuovo problema</div>
                <CreateProblem />
                <hr />
                <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>
        </>
    )
}
