import React, { useState } from "react" import { zodResolver } from "@hookform/resolvers/zod" import { Button, Heading, Text } from "@medusajs/ui" import { Resolver, useFieldArray, useForm } from "react-hook-form" import { useTranslation } from "react-i18next" import { z } from "zod" import { Form } from "../../../components/common/form" import { StackedFocusModal } from "../../../components/modals" import { KeyboundForm } from "../../../components/utilities/keybound-form" import { TieredPriceFormProps, TieredPriceSchema } from "./types" import { TieredPriceList } from "./tiered-price-list" import { TieredPriceItem } from "./tiered-price-item" import { getRuleValue } from "./tiered-price-list" export const TieredPriceForm = ({ schema, initialValues, onSubmit, onClose, currency, header, description, addPriceLabel, fieldConfig, defaultRow, renderConditionItem, renderConditionTrigger, }: TieredPriceFormProps) => { const { t } = useTranslation() const [value, setValue] = useState([getRuleValue(0)]) const emptyRow = defaultRow ?? ({ amount: "", [fieldConfig.min]: "", [fieldConfig.max]: null } as any) const form = useForm, any, z.infer>({ defaultValues: { prices: initialValues.length > 0 ? initialValues : [emptyRow], } as any, // The schema is only known through the generic `T`, so the resolver's // inferred types can't be related back to `z.infer` here. resolver: zodResolver(schema as any) as unknown as Resolver< z.infer, any, z.infer >, }) const { fields, append, remove } = useFieldArray({ control: form.control, name: "prices" as any, }) const handleAdd = () => { append(emptyRow as any) setValue([...value, getRuleValue(fields.length)]) } const handleRemove = (index: number) => { remove(index) } const handleSubmit = async (event?: React.BaseSyntheticEvent) => { try { await form.handleSubmit( (values) => { onSubmit(values) onClose() }, (e) => { const indexesWithErrors = Object.keys(e.prices || {}) setValue((prev) => { const values = new Set(prev) indexesWithErrors.forEach((index) => { values.add(getRuleValue(Number(index))) }) return Array.from(values) }) } )(event) } catch (error) { console.error("Unexpected form submission error:", error) } } const handleOnKeyDown = (event: React.KeyboardEvent) => { if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) { event.preventDefault() event.stopPropagation() handleSubmit() } } return (
{header} {description}
{fields.map((field, index) => ( {renderConditionItem({ index, control: form.control, currency, })} ))}
) }