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


export interface OptionalInputProps<A extends Option.Option<T>, T, R>
extends
    Omit<useInput.Options<A, R>, "schema">
{}

export const OptionalInput = <A extends Option.Option<T>, T, R>(
    schema: Schema.Schema<A, string, R>
): Component.Component<
    OptionalInputProps<A, T, R>,
    React.JSX.Element,
    ParseResult.ParseError,
    R
> => Component.makeUntraced(function* OptionalInput(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, i) => <li key={i}>{issue.message}</li>)}</ul>
                    </Callout.Text>
                </Callout.Root>
            }

            <TextField.Root
                value={input.value}
                onChange={input.onChange}
                {...Struct.omit(props, "ref")}
            />
        </Flex>
    )
})
