import { route } from 'preact-router'
import { useState } from 'preact/hooks'
import { isAdministrator, Solution as SolutionModel, User } from '../../shared/model'
import { server } from '../api'
import { Header } from '../components/Header'
import { Select } from '../components/Select'
import { Solution } from '../components/Solution'
import { useCurrentUser, useResource } from '../hooks'

const SolutionList = ({ user }: { user: User }) => {
    const [solutions, refresh] = useResource<SolutionModel[]>(`/api/solutions?user=${user.id}`, [])

    return (
        <div class="solution-list">
            {solutions.map(({ forProblem, content, status }) => (
                <Solution
                    {...{ forProblem, content, status }}
                    adminControls={isAdministrator(user.role)}
                />
            ))}
        </div>
    )
}

export const ProfilePage = ({}) => {
    const [user, logout] = useCurrentUser(user => {
        if (!user) {
            route('/login', true)
        }
    })

    const handleLogout = () => {
        logout()
        route('/')
    }

    return (
        user && (
            <main class="page-profile">
                <Header {...{ user }} />
                <div class="subtitle">Le tue soluzioni</div>
                <SolutionList {...{ user }} />
                <div class="subtitle">Altro</div>
                <button onClick={handleLogout}>Logout</button>
            </main>
        )
    )
}
