import { Callout, Flex, TextField } from "@radix-ui/themes"
import { Option, ParseResult, Schema } from "effect"
import { Component } from "effect-fc"
import { useInput } from "effect-fc/hooks"
import * as React from "react"


export interface TextFieldInputProps<A, R> extends Omit<useInput.Options<A, R>, "schema"> {
    readonly textFieldRootProps: Omit<TextField.RootProps, "children">
    readonly children?: React.ReactNode
}

export const TextFieldInput = <A, R>(
    schema: Schema.Schema<A, string, R>
): Component.Component<
    TextFieldInputProps<A, R>,
    React.JSX.Element,
    ParseResult.ParseError,
    R
> => Component.makeUntraced(function* TextFieldInput(props) {
    const input = yield* useInput({ schema, ...props })
    const issues = React.useMemo(() => Option.map(
        input.error,
        ParseResult.ArrayFormatter.formatErrorSync,
    ), [input.error])

    return (
        <Flex direction="column" gap="1">
            {Option.isSome(issues) &&
                <Callout.Root color="red" role="alert">
                    <Callout.Text>
                        <ul>
                            {issues.value.map(issue => <li>{issue.message}</li>)}
                        </ul>
                    </Callout.Text>
                </Callout.Root>
            }

            <TextField.Root
                value={input.value}
                onChange={input.onChange}
                {...props.textFieldRootProps}
            >
                {props.children}
            </TextField.Root>
        </Flex>
    )
})
