import React, { ReactNode } from "react";
import { FormFieldProps } from "react-compose-form";
import { FormFieldContext, FormItem, FormLabel, FormControl } from "@/components/ui/form";
import { FormMessage } from "@/components/form";
import { Input, InputProps } from "@/components/ui/input";

export type TextFieldProps = FormFieldProps<{
    containerClassName?: string;
    className?: string;
    inline?: boolean;
    label?: string;
    type?: InputProps["type"];
    placeholder?: InputProps["placeholder"];
    max?: InputProps["max"];
    min?: InputProps["min"];
    helperText?: string | ReactNode;
}>;

export const InputField: React.FC<TextFieldProps> = (props) => {
    const {
        label,
        name,
        type = "text",
        value = "",
        containerClassName,
        helperText,
        ...rest
    } = props;

    if(type === "hidden") {
        return (
            <input {...rest} name={name} type={type} value={value || ""} />
        );
    }

    return (
        <FormFieldContext
          value={{ name: name as string }}>
            <FormItem className={containerClassName}>
                {label && (
                    <FormLabel>{label}</FormLabel>
                )}

                <FormControl>
                    <Input
                      {...rest}
                      type={type}
                      name={name}
                      value={value || ""} />
                </FormControl>

                <FormMessage absolute name={name as string}>
                    {helperText}
                </FormMessage>
            </FormItem>
        </FormFieldContext>
    );
};
