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

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

export const SwitchField: React.FC<SwitchFieldProps> = (props) => {
    const {
        label,
        name,
        helperText,
        value = false,
        onChange
    } = props;

    return (
        <FormFieldContext value={{ name: name as string }}>
            <FormItem>
                {label && (
                    <FormLabel className="col-start-2">
                        {label}
                    </FormLabel>
                )}

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

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