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


export type TextFieldInputProps<A, R> = (
    & (
        | { readonly optional: true } & Omit<useInput.Options<Option.Option<A>, R>, "schema">
        | { readonly optional?: false } & Omit<useInput.Options<A, R>, "schema">
    )
    & Omit<TextField.RootProps, "ref">
)

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 ref = React.useMemo(() => props.optional
        ? SubscriptionSubRef.makeFromGetSet(props.ref, {

        })
        : props.ref,
    [props.optional, props.ref])
    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>
    )
})
