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/form-message";
import { Select } from "@/components/ui/select";

export type SelectFieldProps = FormFieldProps<{
    containerClassName?: string;
    className?: string;
    label?: string;
    children?: ReactNode;
    helperText?: string | ReactNode;
}>;

export const SelectField: React.FC<SelectFieldProps> = (props) => {
    const {
        containerClassName,
        label,
        helperText,
        name,
        value,
        children,
        onChange
    } = props;

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

                <FormControl>
                    <Select
                      name={name}
                      value={value}
                      defaultValue={value}
                      onValueChange={onChange}>
                        {children}
                    </Select>
                </FormControl>

                {name && (
                    <FormMessage absolute name={name}>
                        {helperText}
                    </FormMessage>
                )}
            </FormItem>
        </FormFieldContext>
    );
};
