import React, { ReactNode } from "react";
import { FormFieldProps } from "react-compose-form";
import { FormFieldContext, FormItem, FormLabel, FormControl } from "@/components/ui/form";
import { Checkbox } from "@/components/ui/checkbox";
import { FormMessage } from "@/components/form/form-message";

export type CheckboxFieldProps = FormFieldProps<{
    label?: string;
    helperText?: ReactNode;
}>;

export const CheckboxField: React.FC<CheckboxFieldProps> = (props) => {
    const {
        label,
        helperText,
        name,
        value,
        onChange,
        ...rest
    } = props;

    return (
        <FormFieldContext
          value={{
            name: name as string
          }}>
            <FormItem className="gap-1 grid-cols-[20px_auto]">
                {label && (
                    <FormLabel className="col-start-2">
                        {label}
                    </FormLabel>
                )}

                <FormControl className="col-start-1 row-start-1">
                    <Checkbox
                      {...rest}
                      checked={value}
                      onCheckedChange={onChange} />
                </FormControl>

                <FormMessage
                  className="col-start-2 row-start-2"
                  absolute
                  name={name!}>
                    {helperText}
                </FormMessage>
            </FormItem>
        </FormFieldContext>
    );
};
