1 import {
2 ComponentPropsWithoutRef,
3 forwardRef,
4 useImperativeHandle,
5 useRef,
6 } from "react"
7 import { Select } from "@medusajs/ui"
8 import { useTranslation } from "react-i18next"
9 import { getCountryProvinceObjectByIso2 } from "../../../lib/data/country-states"
10
11 export const ProvinceSelect = forwardRef<
12 HTMLButtonElement,
13 ComponentPropsWithoutRef<typeof Select> & {
14 placeholder?: string
15 defaultValue?: string
16 country_code: string
17 valueAs?: "iso_2" | "name"
18 onChange?: (value: string) => void
19 }
20 >(
21 (
22 {
23 disabled,
24 placeholder,
25 defaultValue,
26 country_code,
27 valueAs = "iso_2",
28 onChange,
29 ...field
30 },
31 ref
32 ) => {
33 const { t } = useTranslation()
34 const innerRef = useRef<HTMLButtonElement>(null)
35
36 useImperativeHandle(ref, () => innerRef.current as HTMLButtonElement)
37
38 const provinceObject = getCountryProvinceObjectByIso2(country_code)
39
40 if (!provinceObject) {
41 disabled = true
42 }
43
44 const options = Object.entries(provinceObject?.options ?? {}).map(
45 ([iso2, name]) => {
46 return (
47 <Select.Item
48 key={iso2}
49 value={valueAs === "iso_2" ? iso2.toLowerCase() : name}
50 >
51 {name}
52 </Select.Item>
53 )
54 }
55 )
56
57 const placeholderText = provinceObject
58 ? t(`taxRegions.fields.sublevels.placeholders.${provinceObject.type}`)
59 : ""
60
61 return (
62 <div className="relative">
63 <Select
64 {...field}
65 value={
66 field.value
67 ? valueAs === "iso_2"
68 ? field.value.toLowerCase()
69 : field.value
70 : undefined
71 }
72 defaultValue={
73 defaultValue
74 ? valueAs === "iso_2"
75 ? defaultValue.toLowerCase()
76 : defaultValue
77 : undefined
78 }
79 onValueChange={onChange}
80 disabled={disabled}
81 >
82 <Select.Trigger ref={innerRef} className="w-full">
83 <Select.Value placeholder={placeholder || placeholderText} />
84 </Select.Trigger>
85 <Select.Content>{options}</Select.Content>
86 </Select>
87 </div>
88 )
89 }
90 )
91 ProvinceSelect.displayName = "ProvinceSelect"