import type { ComponentProps } from "react"; import { DateInput } from "@mantine/dates"; import { useController, useFormContext } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { bankDateInputValue } from "../../model/form-validation"; import { type BankCardValues, bankDateSchema } from "../../model/form.schema"; function useBankCardFieldsVm() { const { control, formState: { errors }, register, } = useFormContext(); const { t } = useTranslation(); const { field: paymentSystemField } = useController({ control, name: "paymentSystem", }); const { field: openingDateField } = useController({ control, name: "openingDate", }); const paymentSystems = ["mir", "visa", "mastercard"].map(value => ({ label: t(`bank.paymentSystems.${value}`), value, })); const onPaymentSystemChange: (value: null | string) => void = value => paymentSystemField.onChange(value ?? ""); const dateParser: ComponentProps["dateParser"] = value => bankDateSchema.safeParse(bankDateInputValue(value)).success ? bankDateInputValue(value) : null; // eslint-disable-line unicorn/no-null -- Mantine represents an empty controlled openingDateField as null. const onOpeningDateBlur: ComponentProps["onBlur"] = ( event, ) => { openingDateField.onChange(bankDateInputValue(event.currentTarget.value)); openingDateField.onBlur(); }; const onOpeningDateChange: (value: null | string) => void = value => openingDateField.onChange(value ?? ""); const onOpeningDateInput: ComponentProps["onInput"] = event => openingDateField.onChange(bankDateInputValue(event.currentTarget.value)); const openingDateValue = bankDateSchema.safeParse(openingDateField.value) .success ? openingDateField.value : undefined; return { dateParser, errors, onOpeningDateBlur, onOpeningDateChange, onOpeningDateInput, onPaymentSystemChange, openingDateField, openingDateValue, paymentSystemField, paymentSystems, register, t, }; } export { useBankCardFieldsVm };