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

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

    const [user, logout] = useCurrentUser(user => {
        if (user) {
            server.get(`/api/solutions?user=${user.id}`).then(solutions => {
                setSolutions(solutions)
            })
        } else {
            route('/login', true)
        }
    })

    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>
        )
    )
}
