import { Widgets } from '@mui/icons-material' import { Autocomplete, Box, Button, Card, Chip, FormControl, FormLabel, Input, ListItem, ListItemContent, ListItemDecorator, Option, Select, TextField, Typography, } from '@mui/joy' import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' const isValidTrigger = (thing, condition, triggerState) => { const newErrors = {} if (!thing || !triggerState) { newErrors.thing = 'Please select a thing and trigger state' return false } if (thing.type === 'boolean') { if (['true', 'false'].includes(triggerState)) { return true } else { newErrors.type = 'Boolean type does not require a condition' return false } } if (thing.type === 'number') { if (isNaN(triggerState)) { newErrors.triggerState = 'Trigger state must be a number' return false } if (['eq', 'neq', 'gt', 'gte', 'lt', 'lte'].includes(condition)) { return true } } if (thing.type === 'text') { if (typeof triggerState === 'string') { return true } } newErrors.triggerState = 'Trigger state must be a number' return false } const ThingTriggerSection = ({ things, onTriggerUpdate, onValidate, selected, isAttepmtingToSave, }) => { const [selectedThing, setSelectedThing] = useState(null) const [condition, setCondition] = useState(null) const [triggerState, setTriggerState] = useState(null) const navigate = useNavigate() useEffect(() => { if (selected) { setSelectedThing(things?.find(t => t.id === selected.thingId)) setCondition(selected.condition) setTriggerState(selected.triggerState) } }, [things]) useEffect(() => { if (selectedThing && triggerState) { onTriggerUpdate({ thing: selectedThing, condition: condition, triggerState: triggerState, }) } if (isValidTrigger(selectedThing, condition, triggerState)) { onValidate(true) } else { onValidate(false) } }, [selectedThing, condition, triggerState]) return ( Trigger a task when a thing state changes to a desired state {things.length !== 0 && ( it's look like you don't have any things yet, create a thing to trigger a task when the state changes. {' '} to create a thing )} setSelectedThing(newValue)} getOptionLabel={option => option.name} renderOption={(props, option) => ( {option.name} type: {option.type}{' '} state: {option.state} )} renderInput={params => ( )} /> Create a condition to trigger a task when the thing state changes to desired state {selectedThing?.type == 'boolean' && ( When the state of {selectedThing.name} changes as specified below, the task will become due. )} {selectedThing?.type == 'number' && ( When the state of {selectedThing.name} changes as specified below, the task will become due. State is setTriggerState(e.target.value)} sx={{ width: '50%' }} /> )} {selectedThing?.type == 'text' && ( When the state of {selectedThing.name} changes as specified below, the task will become due. setTriggerState(e.target.value)} label='Enter the text to trigger the task' /> )} ) } export default ThingTriggerSection