import { Box, FormControl, Input, Typography } from '@mui/joy'
import { useEffect, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import ModalActions from '../../../components/common/ModalActions'
import { useResponsiveModal } from '../../../hooks/useResponsiveModal.js'
import { useNotification } from '../../../service/NotificationProvider.jsx'
import LABEL_COLORS from '../../../utils/Colors.jsx'
import { CreateLabel, UpdateLabel } from '../../../utils/Fetcher'
import { useLabels } from '../../Labels/LabelQueries'
function LabelModal({ isOpen, onClose, label }) {
const { ResponsiveModal } = useResponsiveModal()
const [labelName, setLabelName] = useState('')
const [color, setColor] = useState('')
const [error, setError] = useState('')
const { data: userLabels = [] } = useLabels()
const queryClient = useQueryClient()
const { showError } = useNotification()
// 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
}
const handleSave = () => {
if (!validateLabel()) return
const saveLabel = label?.id && label.id !== -1 ? UpdateLabel : CreateLabel
saveLabel({
id: label?.id,
name: labelName,
color,
})
.then(res => {
if (res?.error) {
setError(res.error)
} else {
queryClient.invalidateQueries('labels')
onClose()
}
})
.catch(err => {
if (err.queued) {
showError({
title: 'Failed to save label',
message: 'Unable to save label. Please try again.',
})
} else {
showError({
title: 'Failed to save label',
message: 'Unable to save label. Please try again.',
})
}
})
}
return (
}
>
Name
setLabelName(e.target.value)}
/>
Color
{LABEL_COLORS.map(colorOption => (
setColor(colorOption.value)}
sx={{
width: 40,
height: 40,
border: 0,
p: 0,
borderRadius: '50%',
background: colorOption.value,
cursor: 'pointer',
outline:
color === colorOption.value
? '3px solid var(--joy-palette-primary-500)'
: '2px solid transparent',
outlineOffset: '2px',
transition: 'all 0.15s ease',
flexShrink: 0,
'&:hover': { transform: 'scale(1.2)' },
}}
/>
))}
{error && (
{error}
)}
)
}
export default LabelModal