1 import React, { useState } from "react"
2 import { zodResolver } from "@hookform/resolvers/zod"
3 import { Button, Heading, Text } from "@medusajs/ui"
4 import { Resolver, useFieldArray, useForm } from "react-hook-form"
5 import { useTranslation } from "react-i18next"
6 import { z } from "zod"
7 import { Form } from "../../../components/common/form"
8 import { StackedFocusModal } from "../../../components/modals"
9 import { KeyboundForm } from "../../../components/utilities/keybound-form"
10 import { TieredPriceFormProps, TieredPriceSchema } from "./types"
11 import { TieredPriceList } from "./tiered-price-list"
12 import { TieredPriceItem } from "./tiered-price-item"
13 import { getRuleValue } from "./tiered-price-list"
14
15 export const TieredPriceForm = <T extends TieredPriceSchema>({
16 schema,
17 initialValues,
18 onSubmit,
19 onClose,
20 currency,
21 header,
22 description,
23 addPriceLabel,
24 fieldConfig,
25 defaultRow,
26 renderConditionItem,
27 renderConditionTrigger,
28 }: TieredPriceFormProps<T>) => {
29 const { t } = useTranslation()
30 const [value, setValue] = useState<string[]>([getRuleValue(0)])
31
32 const emptyRow =
33 defaultRow ??
34 ({ amount: "", [fieldConfig.min]: "", [fieldConfig.max]: null } as any)
35
36 const form = useForm<z.infer<T>, any, z.infer<T>>({
37 defaultValues: {
38 prices: initialValues.length > 0 ? initialValues : [emptyRow],
39 } as any,
40 // The schema is only known through the generic `T`, so the resolver's
41 // inferred types can't be related back to `z.infer<T>` here.
42 resolver: zodResolver(schema as any) as unknown as Resolver<
43 z.infer<T>,
44 any,
45 z.infer<T>
46 >,
47 })
48
49 const { fields, append, remove } = useFieldArray({
50 control: form.control,
51 name: "prices" as any,
52 })
53
54 const handleAdd = () => {
55 append(emptyRow as any)
56
57 setValue([...value, getRuleValue(fields.length)])
58 }
59
60 const handleRemove = (index: number) => {
61 remove(index)
62 }
63
64 const handleSubmit = async (event?: React.BaseSyntheticEvent) => {
65 try {
66 await form.handleSubmit(
67 (values) => {
68 onSubmit(values)
69 onClose()
70 },
71 (e) => {
72 const indexesWithErrors = Object.keys(e.prices || {})
73 setValue((prev) => {
74 const values = new Set(prev)
75
76 indexesWithErrors.forEach((index) => {
77 values.add(getRuleValue(Number(index)))
78 })
79
80 return Array.from(values)
81 })
82 }
83 )(event)
84 } catch (error) {
85 console.error("Unexpected form submission error:", error)
86 }
87 }
88
89 const handleOnKeyDown = (event: React.KeyboardEvent<HTMLFormElement>) => {
90 if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
91 event.preventDefault()
92 event.stopPropagation()
93 handleSubmit()
94 }
95 }
96
97 return (
98 <Form {...form}>
99 <KeyboundForm
100 onSubmit={handleSubmit}
101 onKeyDown={handleOnKeyDown}
102 className="flex h-full flex-col"
103 >
104 <StackedFocusModal.Content>
105 <StackedFocusModal.Header />
106 <StackedFocusModal.Body className="size-full overflow-hidden">
107 <div className="flex size-full flex-1 flex-col items-center overflow-y-auto">
108 <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-6 py-16">
109 <div className="flex w-full flex-col gap-y-6">
110 <div>
111 <StackedFocusModal.Title asChild>
112 <Heading>{header}</Heading>
113 </StackedFocusModal.Title>
114 <StackedFocusModal.Description asChild>
115 <Text size="small" className="text-ui-fg-subtle">
116 {description}
117 </Text>
118 </StackedFocusModal.Description>
119 </div>
120 <TieredPriceList value={value} onValueChange={setValue}>
121 {fields.map((field, index) => (
122 <TieredPriceItem
123 key={field.id}
124 index={index}
125 onRemove={handleRemove}
126 currency={currency}
127 control={form.control}
128 triggerContent={renderConditionTrigger({
129 index,
130 control: form.control,
131 currency,
132 })}
133 >
134 {renderConditionItem({
135 index,
136 control: form.control,
137 currency,
138 })}
139 </TieredPriceItem>
140 ))}
141 </TieredPriceList>
142 <div className="flex items-center justify-end">
143 <Button
144 variant="secondary"
145 size="small"
146 type="button"
147 onClick={handleAdd}
148 >
149 {addPriceLabel}
150 </Button>
151 </div>
152 </div>
153 </div>
154 </div>
155 </StackedFocusModal.Body>
156 <StackedFocusModal.Footer>
157 <div className="flex items-center justify-end gap-2">
158 <StackedFocusModal.Close asChild>
159 <Button variant="secondary" size="small" type="button">
160 {t("actions.cancel")}
161 </Button>
162 </StackedFocusModal.Close>
163 <Button size="small" type="button" onClick={handleSubmit}>
164 {t("actions.save")}
165 </Button>
166 </div>
167 </StackedFocusModal.Footer>
168 </StackedFocusModal.Content>
169 </KeyboundForm>
170 </Form>
171 )
172 }