import { FC } from "react";
import { IconCheck, IconX } from "@tabler/icons-react";
import { Button, Group, Stack, TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { useProjectsContext } from "@/app/deals/contexts/ProjectsContext";
import { ClientSchema } from "@/lib/client";
import ClientSelect from "@/modules/dealModularEditorTabs/Clients/components/ClientSelect";
import { ModuleNames } from "@/modules/modules";

export type CreateDealForm = {
    name: string;
    client?: ClientSchema;
    clientId?: number;
};

type Props = {
    onSubmit: (values: CreateDealForm) => void;
    onCancel: () => void;
};

const CreateCardForm: FC<Props> = ({ onSubmit, onCancel }) => {
    const { modulesSet } = useProjectsContext();

    const form = useForm<CreateDealForm>({
        initialValues: {
            name: "",
        },
        validate: {
            name: value => !value && "Введите название",
            client: client =>
                modulesSet.has(ModuleNames.CLIENTS) &&
                !client &&
                "Выберите клиента",
        },
    });

    return (
        <form
            onSubmit={form.onSubmit(values => {
                onSubmit(values);
                form.reset();
            })}>
            <Stack>
                <TextInput
                    placeholder={"Название"}
                    {...form.getInputProps("name")}
                />
                {modulesSet.has(ModuleNames.CLIENTS) && (
                    <ClientSelect
                        placeholder={"Клиент"}
                        {...form.getInputProps("client")}
                        onChange={client => {
                            form.setFieldValue("client", client);
                            form.setFieldValue("clientId", client?.id);
                        }}
                    />
                )}
                <Group wrap={"nowrap"}>
                    <Button
                        variant={"default"}
                        w={"100%"}
                        onClick={onCancel}>
                        <IconX />
                    </Button>
                    <Button
                        variant={"default"}
                        w={"100%"}
                        type={"submit"}>
                        <IconCheck />
                    </Button>
                </Group>
            </Stack>
        </form>
    );
};

export default CreateCardForm;
