aboutsummaryrefslogtreecommitdiffstats
path: root/src/views/ChoreEdit/ChoreView.jsx
blob: 811627004309bdf2c2f56568bddf25894a840367 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import {
  CalendarMonth,
  CancelScheduleSend,
  Check,
  Checklist,
  PeopleAlt,
  Person,
} from '@mui/icons-material'
import {
  Box,
  Button,
  Container,
  Grid,
  ListItem,
  ListItemContent,
  ListItemDecorator,
  Sheet,
  Snackbar,
  styled,
  Typography,
} from '@mui/joy'
import moment from 'moment'
import { useEffect, useState } from 'react'
import { useParams, useSearchParams } from 'react-router-dom'
import {
  GetAllUsers,
  GetChoreDetailById,
  MarkChoreComplete,
} from '../../utils/Fetcher'
const IconCard = styled('div')({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  backgroundColor: '#f0f0f0', // Adjust the background color as needed
  borderRadius: '50%',
  minWidth: '50px',
  height: '50px',
  marginRight: '16px',
})
const ChoreView = () => {
  const [chore, setChore] = useState({})

  const [performers, setPerformers] = useState([])
  const [infoCards, setInfoCards] = useState([])
  const { choreId } = useParams()

  // query param `complete=true`

  const [searchParams] = useSearchParams()

  const [isPendingCompletion, setIsPendingCompletion] = useState(false)
  const [timeoutId, setTimeoutId] = useState(null)
  const [secondsLeftToCancel, setSecondsLeftToCancel] = useState(null)
  useEffect(() => {
    Promise.all([
      GetChoreDetailById(choreId).then(resp => {
        if (resp.ok) {
          return resp.json().then(data => {
            setChore(data.res)
          })
        }
      }),
      GetAllUsers()
        .then(response => response.json())
        .then(data => {
          setPerformers(data.res)
        }),
    ])
    const auto_complete = searchParams.get('auto_complete')
    if (auto_complete === 'true') {
      handleTaskCompletion()
    }
  }, [])
  useEffect(() => {
    if (chore && performers.length > 0) {
      generateInfoCards(chore)
    }
  }, [chore, performers])

  const generateInfoCards = chore => {
    const cards = [
      {
        icon: <CalendarMonth />,
        text: 'Due Date',
        subtext: moment(chore.dueDate).format('MM/DD/YYYY hh:mm A'),
      },
      {
        icon: <PeopleAlt />,
        text: 'Assigned To',
        subtext: performers.find(p => p.id === chore.assignedTo)?.displayName,
      },
      {
        icon: <Person />,
        text: 'Created By',
        subtext: performers.find(p => p.id === chore.createdBy)?.displayName,
      },
      //   {
      //     icon: <TextFields />,
      //     text: 'Frequency',
      //     subtext:
      //       chore.frequencyType.charAt(0).toUpperCase() +
      //       chore.frequencyType.slice(1),
      //   },
      {
        icon: <Checklist />,
        text: 'Total Completed',
        subtext: `${chore.totalCompletedCount}`,
      },
      //   {
      //     icon: <Timelapse />,
      //     text: 'Last Completed',
      //     subtext:
      //       chore.lastCompletedDate &&
      //       moment(chore.lastCompletedDate).format('MM/DD/YYYY hh:mm A'),
      //   },
      {
        icon: <Person />,
        text: 'Last Completed',
        subtext: chore.lastCompletedDate
          ? `${
              chore.lastCompletedDate &&
              moment(chore.lastCompletedDate).format('MM/DD/YYYY hh:mm A')
            }(${
              performers.find(p => p.id === chore.lastCompletedBy)?.displayName
            })`
          : 'Never',
      },
    ]
    setInfoCards(cards)
  }
  const handleTaskCompletion = () => {
    setIsPendingCompletion(true)
    let seconds = 3 // Starting countdown from 3 seconds
    setSecondsLeftToCancel(seconds)

    const countdownInterval = setInterval(() => {
      seconds -= 1
      setSecondsLeftToCancel(seconds)

      if (seconds <= 0) {
        clearInterval(countdownInterval) // Stop the countdown when it reaches 0
      }
    }, 1000)

    const id = setTimeout(() => {
      MarkChoreComplete(choreId)
        .then(resp => {
          if (resp.ok) {
            return resp.json().then(data => {
              setChore(data.res)
            })
          }
        })
        .then(() => {
          setIsPendingCompletion(false)
          clearTimeout(id)
          clearInterval(countdownInterval) // Ensure to clear this interval as well
          setTimeoutId(null)
          setSecondsLeftToCancel(null)
        })
        .then(() => {
          // refetch the chore details
          GetChoreDetailById(choreId).then(resp => {
            if (resp.ok) {
              return resp.json().then(data => {
                setChore(data.res)
              })
            }
          })
        })
    }, 3000)

    setTimeoutId(id)
  }

  return (
    <Container maxWidth='sm'>
      <Sheet
        variant='plain'
        sx={{
          borderRadius: 'sm',
          p: 2,
          boxShadow: 'md',
          minHeight: '90vh',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
        }}
      >
        <Box>
          <Typography
            level='h4'
            textAlign={'center'}
            sx={{
              mt: 2,
              mb: 4,
            }}
          >
            {chore.name}
          </Typography>

          <Grid container spacing={1}>
            {infoCards.map((info, index) => (
              <Grid key={index} item xs={12} sm={6}>
                <Sheet
                  sx={{ mb: 1, borderRadius: 'md', p: 1, boxShadow: 'sm' }}
                >
                  <ListItem>
                    <ListItemDecorator>
                      <IconCard>{info.icon}</IconCard>
                    </ListItemDecorator>
                    <ListItemContent>
                      <Typography level='body1' sx={{ fontWeight: 'md' }}>
                        {info.text}
                      </Typography>
                      <Typography level='body1' color='text.tertiary'>
                        {info.subtext ? info.subtext : '--'}
                      </Typography>
                    </ListItemContent>
                  </ListItem>
                </Sheet>
              </Grid>
            ))}
          </Grid>
        </Box>
        <Box
          sx={{
            mt: 6,
          }}
        >
          <Button
            fullWidth
            size='lg'
            sx={{
              height: 50,
              mb: 2,
            }}
            onClick={handleTaskCompletion}
            disabled={isPendingCompletion}
            color={isPendingCompletion ? 'danger' : 'success'}
            startDecorator={<Check />}
          >
            <Box>Mark as done</Box>
          </Button>
          {/* <Button
            sx={{
              borderRadius: '32px',
              mt: 1,
              height: 50,
              zIndex: 1,
            }}
            onClick={() => {
              Navigate('/my/chores')
            }}
            color={isPendingCompletion ? 'danger' : 'success'}
            startDecorator={isPendingCompletion ? <Close /> : <Check />}
            fullWidth
          >
            <Box>Mark as {isPendingCompletion ? 'completed' : 'done'}</Box>
          </Button> */}
        </Box>
      </Sheet>
      <Snackbar
        open={isPendingCompletion}
        endDecorator={
          <Button
            onClick={() => {
              if (timeoutId) {
                clearTimeout(timeoutId)
                setIsPendingCompletion(false)
                setTimeoutId(null)
                setSecondsLeftToCancel(null) // Reset or adjust as needed
              }
            }}
            size='md'
            variant='outlined'
            color='primary'
            startDecorator={<CancelScheduleSend />}
          >
            Cancel
          </Button>
        }
      >
        <Typography level='body2' textAlign={'center'}>
          Task will be marked as completed in {secondsLeftToCancel} seconds
        </Typography>
      </Snackbar>
    </Container>
  )
}

export default ChoreView