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

type RouteProps = {
    id: string
}

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

    const [user] = useCurrentUser()

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

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

    const [solutions] = useReadResource<SolutionModel[]>(`/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>
    )
}
