import { useContext, useEffect, useRef, useState } from 'preact/hooks'
import { server } from '../api.jsx'
import { Header } from '../components/Header.jsx'
import { MarkdownEditor } from '../components/MarkdownEditor.jsx'
import { Problem } from '../components/Problem.jsx'
import { Solution } from '../components/Solution.jsx'
import { MetadataContext, useCurrentUser, useReadResource } from '../hooks.jsx'

export const ProblemPage = ({ id }) => {
    const metadata = useContext(MetadataContext)
    metadata.title = `Problem ${id}`

    const [user] = useCurrentUser()

    const [source, setSource] = useState('')

    const [{ content }] = useReadResource(`/api/problem/${id}`, { content: '' })

    const [solutions] = useReadResource(`/api/solutions?problem=${id}`, [])

    const sendSolution = async () => {
        await server.post('/api/solution', {
            forProblem: id,
            content: source,
        })

        location.reload()
    }

    return (
        <main class="page-problem">
            <Header {...{ user }} />
            <div class="subtitle">Testo del problema</div>
            <Problem id={id} content={content} />
            {solutions.length > 0 && (
                <details>
                    <summary>Soluzioni</summary>
                    <div class="solution-list">
                        {solutions.map(s => (
                            <Solution {...s} />
                        ))}
                    </div>
                </details>
            )}
            {user && (
                <>
                    <div class="subtitle">Invia una soluzione al problema</div>
                    <MarkdownEditor {...{ source, setSource }} />
                    <button onClick={sendSolution}>Invia Soluzione</button>
                </>
            )}
        </main>
    )
}
