text: import React, { useEffect } from 'react'
  import { formatDateStr, handleRespError } from '@open-tender/js'
  import { showNotification, addAlert } from '@open-tender/redux'
  import {
    Page,
    Section,
    SectionHeader,
    Row,
    RowHeader,
    RowTable,
    InfoList,
    Loading,
    ErrorMessage,
    Scrollable,
    Button,
  } from '@open-tender/components-pos'
  import { useDispatch, useSelector } from 'react-redux'
  import {
    fetchPunches,
    selectApi,
    selectPunches,
    selectPunchesBusinessDate,
    selectTimezone,
  } from '../../slices'
  import { processPunchees, punchTypes } from '../../utils'
  import { format } from 'date-fns'
  import styled from '@emotion/styled'
  
  const headers = [
    'Department',
    'Punch In',
    'Punch Out',
    'Time On Clock',
    'Time On Break',
    ' ',
  ]
  const width = '18%'
  const widths = [width, width, width, width, width, '10%']
  
  const fmtPunchTime = (date) => {
    return format(date, 'h:mma').toLowerCase()
  }
  
  const CellAlert = styled('span')`
    color: ${(props) => props.theme.colors.alert};
  `
  
  const makeShiftTime = (seconds) => {
    const hours = Math.floor(seconds / 3600)
    const minutes = parseInt((seconds % 3600) / 60)
      .toString()
      .padStart(2, '0')
    return `${hours}:${minutes}`
  }
  
  const processShift = (shift) => {
    const {
      department,
      punchIn,
      punchOut,
      breakOut,
      netSeconds,
      breakSeconds,
    } = shift
    const inTime = punchIn ? fmtPunchTime(punchIn.date) : 'n/a'
    const outTime = punchOut ? (
      fmtPunchTime(punchOut.date)
    ) : (
      <CellAlert>{breakOut ? 'On Break' : 'On Clock'}</CellAlert>
    )
    const onClock = makeShiftTime(netSeconds)
    const onBreak = makeShiftTime(breakSeconds)
    return [department, inTime, outTime, onClock, onBreak]
  }
  
  const Punches = () => {
    const dispatch = useDispatch()
    const api = useSelector(selectApi)
    const tz = useSelector(selectTimezone)
    const businessDate = useSelector(selectPunchesBusinessDate)
    const dateStr = formatDateStr(businessDate)
    const { punches, loading, error } = useSelector(selectPunches)
  
    useEffect(() => {
      if (businessDate) dispatch(fetchPunches(businessDate))
    }, [businessDate, tz, dispatch])
  
    const punchOut = async (employee_id, department_id) => {
      const data = {
        employee_id,
        department_id,
        punch_type: punchTypes.PUNCH_OUT,
        tips: '0.00',
      }
      try {
        await api.postTimePunch(data)
        dispatch(showNotification('Employee punched out!'))
        dispatch(fetchPunches(businessDate))
      } catch (err) {
        const { detail } = handleRespError(err)
        dispatch(addAlert(detail))
      }
    }
  
    return (
      <Page hasSidebar={true}>
        <Section>
          {loading === 'pending' ? (
            <Loading msg="Loading punches" />
          ) : error ? (
            <ErrorMessage error={error} />
          ) : (
            <Scrollable>
              <SectionHeader
                title="Timeclock"
                subtitle="Use this page to review employee time punches for a single business day. Any edits must be made via the Admin Portal."
              />
              <div style={{ padding: '0 0 3rem' }}>
                {!punches.length ? (
                  <p>Looks like there aren't any time punches for {dateStr}.</p>
                ) : (
                  punches.map((employee) => {
                    const {
                      employee_id,
                      timeclock_id,
                      first_name,
                      last_name,
                      role,
                    } = employee
                    const name = `${first_name} ${last_name}`
                    const shifts = processPunchees(employee, tz).map((shift) => {
                      const processed = processShift(shift)
                      const department_id = shift.punchIn
                        ? shift.punchIn.department_id
                        : null
                      const punchOutButton =
                        !shift.punchOut && !shift.breakOut && department_id ? (
                          <Button
                            text="Punch Out"
                            onClick={() => punchOut(employee_id, department_id)}
                            size="xsmall"
                            color="active"
                          />
                        ) : (
                          ' '
                        )
                      return [...processed, punchOutButton]
                    })
                    return (
                      <Row
                        key={employee_id}
                        header={
                          <RowHeader title={name}>
                            <InfoList items={[timeclock_id, role]} />
                          </RowHeader>
                        }
                      >
                        <RowTable
                          headers={headers}
                          widths={widths}
                          rows={shifts}
                        />
                      </Row>
                    )
                  })
                )}
              </div>
            </Scrollable>
          )}
        </Section>
      </Page>
    )
  }
  
  Punches.displayName = 'Punches'
  
  export default Punches
  