"use client";

import {
    Button,
    Flex,
    NumberInput,
    rem,
    Space,
    Text,
    TextInput,
} from "@mantine/core";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import { DealsFiltersForm } from "@/app/deals/hooks/useDealsFilters";
import BoardSelect from "@/components/selects/BoardSelect/BoardSelect";
import StatusSelect from "@/components/selects/StatusSelect/StatusSelect";
import { ProjectSchema } from "@/lib/client";

type Props = {
    value: DealsFiltersForm;
    onChange: (values: DealsFiltersForm) => void;
    project: ProjectSchema | null;
};

const DealsTableFiltersModal = ({
    id,
    context,
    innerProps,
}: ContextModalProps<Props>) => {
    const filtersForm = useForm({
        initialValues: innerProps.value,
    });

    const onSubmit = (values: DealsFiltersForm) => {
        innerProps.onChange(values);
        context.closeModal(id);
    };

    return (
        <form onSubmit={filtersForm.onSubmit(onSubmit)}>
            <Flex
                gap={rem(10)}
                direction={"column"}>
                <NumberInput
                    label={"ID"}
                    placeholder={"Введите ID"}
                    {...filtersForm.getInputProps("id")}
                    value={filtersForm.values.id ?? ""}
                    onChange={value =>
                        typeof value === "number"
                            ? filtersForm.setFieldValue("id", Number(value))
                            : filtersForm.setFieldValue("id", null)
                    }
                    hideControls
                    min={1}
                />
                <TextInput
                    label={"Название"}
                    placeholder={"Введите название"}
                    {...filtersForm.getInputProps("name")}
                />
                <BoardSelect
                    label={"Доска"}
                    {...filtersForm.getInputProps("board")}
                    projectId={innerProps.project?.id}
                    clearable
                />
                <StatusSelect
                    label={"Статус"}
                    {...filtersForm.getInputProps("status")}
                    boardId={filtersForm.values.board?.id}
                    clearable
                    clearOnBoardChange
                />
                <Space />
                <Button
                    variant={"default"}
                    type={"submit"}>
                    <Text>Сохранить</Text>
                </Button>
            </Flex>
        </form>
    );
};

export default DealsTableFiltersModal;
