import _ from "lodash";
import { DetailedHTMLProps, FormHTMLAttributes } from "react";
import { twMerge } from "tailwind-merge";

/**
 * # Form Element
 * @className twui-form
 */
export default function Form<T extends object = { [key: string]: any }>({
    ...props
}: DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement> & {
    submitHandler?: (e: React.FormEvent<HTMLFormElement>, data: T) => void;
}) {
    const finalProps = _.omit(props, "submitHandler");

    return (
        <form
            {...finalProps}
            className={twMerge(
                "flex flex-col items-stretch gap-2 w-full bg-transparent",
                "twui-form",
                props.className
            )}
            onSubmit={(e) => {
                e.preventDefault();
                const formEl = e.target as HTMLFormElement;
                const formData = new FormData(formEl);
                const data = Object.fromEntries(formData.entries()) as T;
                props.submitHandler?.(e, data);
                props.onSubmit?.(e);
            }}
        >
            {props.children}
        </form>
    );
}
