import React, { useEffect, useState } from 'react' import { Box, Button, FormControl, Input, Modal, ModalDialog, Option, Select, Typography, } from '@mui/joy' import { useQueryClient, useMutation } from 'react-query' import { CreateLabel, UpdateLabel } from '../../../utils/Fetcher' import LABEL_COLORS from '../../../utils/LabelColors' import { useLabels } from '../../Labels/LabelQueries' function LabelModal({ isOpen, onClose, label }) { const [labelName, setLabelName] = useState('') const [color, setColor] = useState('') const [error, setError] = useState('') const { data: userLabels = [] } = useLabels() const queryClient = useQueryClient() // Populate the form fields when editing useEffect(() => { if (label) { setLabelName(label.name) setColor(label.color) } else { setLabelName('') setColor('') } setError('') }, [label]) // Validation logic const validateLabel = () => { if (!labelName.trim()) { setError('Name cannot be empty') return false } if ( userLabels.some( userLabel => userLabel.name === labelName && userLabel.id !== label?.id, ) ) { setError('Label with this name already exists') return false } if (!color) { setError('Please select a color') return false } return true } // Mutation for saving labels const saveLabelMutation = useMutation( newLabel => label ? UpdateLabel({ id: label.id, ...newLabel }) : CreateLabel(newLabel), { onSuccess: () => { queryClient.invalidateQueries('labels') onClose() }, onError: () => { setError('Failed to save label. Please try again.') }, }, ) const handleSave = () => { if (!validateLabel()) return saveLabelMutation.mutate({ name: labelName, color }) } return ( {label ? 'Edit Label' : 'Add Label'} Name setLabelName(e.target.value)} /> Color {error && ( {error} )} ) } export default LabelModal