import {UseFormReturnType} from "@mantine/form";
import {Button, Flex, rem} from "@mantine/core";
import {FC} from "react";

type CreateProps<T> = {
    onCreate(values: T): void;
}
type EditProps<T> = {
    onChange(values: T): void;
    element: T;
}

export type CreateEditFormProps<T> = CreateProps<T> | EditProps<T>;

type BaseProps<T> = {
    form: UseFormReturnType<T>
    onClose: () => void;
    closeOnSubmit?: boolean;
    children: React.JSX.Element;
}
type Props<T> = BaseProps<T> & (CreateProps<T> | EditProps<T>);

const BaseFormModal = <T, >(props: Props<T>) => {
    const {closeOnSubmit = false} = props;
    const isEditing = 'onChange' in props;

    const onSubmit = (values: T) => {
        console.log('----values');
        console.log(values)
        if (isEditing) {
            props.onChange(values);
        } else {
            props.onCreate(values);
        }

        if (closeOnSubmit) props.onClose();
    }
    return (
        <form onSubmit={props.form.onSubmit((values) => onSubmit(values))}>
            <Flex gap={rem(10)} direction={"column"}>
                {props.children}
                <Flex justify={"flex-end"} gap={rem(10)}>
                    <Button
                        variant={"subtle"}
                        onClick={() => props.onClose()}
                    >
                        Отменить
                    </Button>
                    <Button
                        type={"submit"}
                        variant={"default"}
                    >
                        Сохранить
                    </Button>
                </Flex>
            </Flex>
        </form>
    )
}
type BodyProps = {
    children: React.JSX.Element;
}
const Body: FC<BodyProps> = ({children}) => {
    return (
        <Flex gap={rem(10)} direction={"column"}>
            {children}
        </Flex>
    )
}
BaseFormModal.Body = Body;
export default BaseFormModal;