import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import ActivityIndicator from "@/components/indicators/activity-indicator"; import { cn } from "@/lib/utils"; import { isMobile } from "react-device-detect"; import { useCallback, useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; type Option = { value: string; label: string; }; type OptionAndInputDialogProps = { open: boolean; title: string; description?: string; options: Option[]; newValueKey: string; initialValue?: string; nameLabel: string; descriptionLabel: string; setOpen: (open: boolean) => void; onSave: (value: string) => Promise; onCreateNew: (name: string, description: string) => Promise; }; export default function OptionAndInputDialog({ open, title, description, options, newValueKey, initialValue, nameLabel, descriptionLabel, setOpen, onSave, onCreateNew, }: OptionAndInputDialogProps) { const { t } = useTranslation("common"); const firstOption = useMemo(() => options[0]?.value, [options]); const [selectedValue, setSelectedValue] = useState( initialValue ?? firstOption, ); const [name, setName] = useState(""); const [descriptionValue, setDescriptionValue] = useState(""); useEffect(() => { if (open) { setSelectedValue(initialValue ?? firstOption); setName(""); setDescriptionValue(""); } }, [open, initialValue, firstOption]); const [isLoading, setIsLoading] = useState(false); const isNew = selectedValue === newValueKey; const disableSave = !selectedValue || (isNew && name.trim().length === 0) || isLoading; const handleSave = useCallback(async () => { if (!selectedValue) { return; } const trimmedName = name.trim(); const trimmedDescription = descriptionValue.trim(); setIsLoading(true); try { if (isNew) { await onCreateNew(trimmedName, trimmedDescription); } else { await onSave(selectedValue); } setOpen(false); } finally { setIsLoading(false); } }, [ selectedValue, name, descriptionValue, isNew, onCreateNew, onSave, setOpen, ]); return ( { if (isMobile) { e.preventDefault(); } }} > {title} {description && {description}}
{isNew && (
setName(e.target.value)} />