import { Button, FormControl, FormField, FormItem, FormLabel, Input, Popover, PopoverContent, PopoverTrigger, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@marzneshin/common/components"; import type { FieldError, FieldErrors } from "react-hook-form"; import { useFormContext } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { ListPlus, MailWarning, TrashIcon } from "lucide-react"; import type { FC } from "react"; import { useState } from "react"; import { noiseTypes } from "../profiles"; interface NoiseForm { noise: Array<{ type: string; packet: string; delay: string; } | null>; } const NoiseErrorPopover: FC<{ errors?: { packet?: FieldError; type?: FieldError; delay?: FieldError }; }> = ({ errors }) => { const { t } = useTranslation(); if (!errors || (!errors.packet && !errors.type && !errors.delay)) return null; return ( {errors.type?.message && ( Type: {t(errors.type.message as string)} )} {errors.packet?.message && ( Packet: {t(errors.packet.message as string)} )} {errors.delay?.message && ( Interval: {t(errors.delay.message as string)} )} ); }; export const NoiseField = () => { const { t } = useTranslation(); const form = useFormContext(); const [forms, setForms] = useState( form.getValues("noise") || [], ); const errors = form.formState.errors as FieldErrors; const addForm = () => { if (forms.length < 5) { const newForms = [ ...forms, { type: "rand", packet: "", delay: "" }, ]; setForms(newForms); form.setValue("noise", newForms, { shouldValidate: true }); } }; const removeForm = (index: number) => { const updatedForms = forms.filter((_, i) => i !== index); setForms(updatedForms); form.setValue("noise", updatedForms, { shouldValidate: true }); }; const enableForm = (index: number) => { const updatedForms = [...forms]; updatedForms[index] = { type: "", packet: "", delay: "" }; setForms(updatedForms); form.setValue("noise", updatedForms, { shouldValidate: true }); }; return ( {forms.length > 0 ? ( forms.map((formData, index) => ( {index === 0 && ( {t("Noise")} {errors.noise?.[index] && ( )} {forms.length < 5 && ( { e.preventDefault(); addForm(); }} > )} )} {formData ? ( <> ( {noiseTypes.map( (option) => ( {option} ), )} )} /> ( )} /> ( )} /> { e.preventDefault(); removeForm(index); }} > > ) : ( { e.preventDefault(); enableForm(index); }} > {t("Enable Form")} )} )) ) : ( {t("Noise")} { e.preventDefault(); addForm(); }} > {t("disabled")} )} ); };