import { useSignal } from '@preact/signals'
import { useEffect } from 'preact/hooks'

type User = {
    uid: string
    gecos: string
}

function applyPatches(users: User[]) {
    users.forEach(user => {
        // strip ",+" from the end of the gecos field
        user.gecos = user.gecos.replace(/,+$/, '')

        // capitalize the first letter of each word
        user.gecos = user.gecos.replace(/\b\w/g, c => c.toUpperCase())
    })
}

export const UtentiPage = () => {
    const utentiSignal = useSignal<User[]>([])

    useEffect(() => {
        fetch('https://poisson.phc.dm.unipi.it/users.json')
            .then(response => response.json())
            .then(data => {
                applyPatches(data)
                utentiSignal.value = data
            })
    }, [])

    return (
        <>
            <div class="search">
                <input type="text" placeholder="Cerca un utente Poisson..." />
                <span class="material-symbols-outlined">search</span>
            </div>
            <div class="search-results">
                {utentiSignal.value.map(user => (
                    <div class="search-result">
                        <div class="icon">
                            <span class="material-symbols-outlined">person</span>
                        </div>
                        <div class="text">{user.gecos}</div>
                        <div class="right">
                            <a href={`https://poisson.phc.dm.unipi.it/~${user.uid}`}>
                                <span class="material-symbols-outlined">globe</span>
                            </a>
                        </div>
                    </div>
                ))}
            </div>
        </>
    )
}
