import { route } from 'preact-router'
import { useState } from 'preact/hooks'
import { server } from '../api.jsx'
import { Header } from '../components/Header.jsx'
import { Solution } from '../components/Solution.jsx'
import { useCurrentUser, useReadResource } from '../hooks.jsx'

export const ProfilePage = ({}) => {
    const [solutions, setSolutions] = useState([])

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

        setSolutions(await server.get(`/api/solutions?user=${user.id}`))
    })

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

    return (
        user && (
            <main class="page-profile">
                <Header {...{ user }} />
                <div class="subtitle">Le tue soluzioni</div>
                <div class="solution-list">
                    {solutions.map(({ forProblem, content }) => (
                        <Solution {...{ forProblem, content }} />
                    ))}
                </div>
                <div class="subtitle">Altro</div>
                <button onClick={handleLogout}>Logout</button>
            </main>
        )
    )
}
