import {
    MizanContext,
    UserContext,
    useEcho,
    useFindUser,
    useMizan,
    useRenameUser,
    useUpdateProfile,
    useUserContext,
    useUserOrders,
    useUserProfile,
    useWhoami,
    type ContextState,
} from '../src/react'
import type { UserContextData } from '../src/index'

export function Screen() {
    return (
        <MizanContext baseUrl="/api/mizan" session={false}>
            <UserContext user_id={1}>
                <Panel />
            </UserContext>
        </MizanContext>
    )
}

function Panel() {
    const context: ContextState<UserContextData> = useUserContext()
    const orders = useUserOrders()
    const profile = useUserProfile()

    const echo = useEcho()
    const findUser = useFindUser()
    const renameUser = useRenameUser()
    const updateProfile = useUpdateProfile()
    const whoami = useWhoami()
    const { call, fetch } = useMizan()

    async function run() {
        const echoed = await echo.mutate({ text: 'hello' })
        const found = await findUser.mutate({ user_id: 1 })
        const renamed = await renameUser.mutate({ user_id: 1, name: 'renamed' })
        const updated = await updateProfile.mutate({ user_id: 1, name: 'renamed' })
        const identity = await whoami.mutate()
        const raw = await call('echo', { text: 'hello' })
        const bundle = await fetch('user', { user_id: 1 })
        console.log(echoed.message, found.name, renamed.name, updated.ok,
                    identity.authenticated, raw, bundle)
    }

    const pending: boolean = echo.isPending
    const failure: Error | null = echo.error

    return (
        <button onClick={run} disabled={pending}>
            {context.status} {orders?.length ?? 0} {profile?.name ?? ''} {failure?.message ?? ''}
        </button>
    )
}
