import { ContextModalProps } from "@mantine/modals";
import { useForm } from "@mantine/form";
import { Flex, NumberInput, rem, TextInput } from "@mantine/core";
import BaseFormModal, { CreateEditFormProps } from "../../../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import { DatePickerInput } from "@mantine/dates";
import TransactionTagsInput from "../components/TransactionTagsInput.tsx";
import { Transaction } from "../types/Transaction.tsx";

type IsIncome = {
    isIncome: boolean;
}
type Props = CreateEditFormProps<Transaction> & IsIncome;

const TransactionFormModal = ({
                                  context,
                                  id,
                                  innerProps,
                              }: ContextModalProps<Props>) => {
    const isEditing = "element" in innerProps;
    const initialValue: Partial<Transaction> = isEditing
        ? innerProps.element
        : {};

    const form = useForm<Partial<Transaction>>({
        initialValues: initialValue,
        validate: {
            name: name => !name && "Необходимо указать наименование",
            amount: amount => !amount && "Необходимо указать сумму",
            spentDate: spentDate => !spentDate && "Необходимо указать дату",
        },
    });
    return (
        <BaseFormModal
            form={form}
            closeOnSubmit
            onClose={() => context.closeContextModal(id)}
            {...innerProps}>
            <BaseFormModal.Body>
                <Flex
                    direction={"column"}
                    gap={rem(10)}>
                    <TextInput
                        label={"Наименование"}
                        placeholder={"Введите наименование"}
                        {...form.getInputProps("name")}
                    />
                    <TextInput
                        label={"Комментарий"}
                        placeholder={"Введите комментарий"}
                        {...form.getInputProps("comment")}
                    />
                    <NumberInput
                        label={"Сумма"}
                        placeholder={"Введите сумму"}
                        min={0}
                        {...form.getInputProps("amount")}
                    />
                    <DatePickerInput
                        {...form.getInputProps("spentDate")}
                        value={form.getInputProps("spentDate").value ? new Date(form.getInputProps("spentDate").value) : null}
                        label={"Дата"}
                        placeholder={"Укажите дату расхода"}
                        valueFormat={"DD.MM.YYYY"}
                    />
                    <TransactionTagsInput
                        {...form.getInputProps("tags")}
                        isIncome={innerProps.isIncome}
                    />
                </Flex>
            </BaseFormModal.Body>
        </BaseFormModal>
    );
};

export default TransactionFormModal;
