import { ReactNode } from "react";
import { Flex } from "@mantine/core";
import { UseFormReturnType } from "@mantine/form";
import BaseFormModalActions from "@/modals/base/BaseFormModal/BaseFormModalActions";

export type CreateProps<TCreate> = {
    onCreate: (values: TCreate) => void;
    isEditing: false;
};

export type EditProps<TEntity, TUpdate> = {
    onChange: (values: TUpdate) => void;
    entity: TEntity;
    isEditing: true;
};

export type CreateEditFormProps<
    TCreate,
    TUpdate = TCreate,
    TEntity = TUpdate,
> = CreateProps<TCreate> | EditProps<TEntity, TUpdate>;

export type BaseFormProps<T> = {
    form: UseFormReturnType<Partial<T>>;
    onClose: () => void;
    closeOnSubmit?: boolean;
    children: ReactNode;
};

type Props<TCreate, TUpdate, TEntity> = BaseFormProps<TEntity> &
    CreateEditFormProps<TCreate, TUpdate, TEntity>;

const BaseFormModal = <TCreate, TUpdate = TCreate, TEntity = TUpdate>(
    props: Props<TCreate, TUpdate, TEntity>
) => {
    const { closeOnSubmit = false } = props;

    const onSubmit = (values: Partial<TEntity>) => {
        if (props.isEditing) {
            props.onChange({ ...props.entity, ...values } as TUpdate);
        } else {
            props.onCreate(values as TCreate);
        }

        if (closeOnSubmit) {
            props.form.reset();
            props.onClose();
        }
    };

    return (
        <form onSubmit={props.form.onSubmit(values => onSubmit(values))}>
            <Flex
                gap={"xs"}
                direction={"column"}>
                {props.children}
                <BaseFormModalActions {...props} />
            </Flex>
        </form>
    );
};

export default BaseFormModal;
