import { hToTime } from 'src/composables/useHelpers'
import { updateTech } from 'src/api/dispatch'

export function useAbsenceResize (pxPerHr, H_START) {
  function startAbsenceResize (e, seg, tech, side) {
    e.preventDefault()
    const startX = e.clientX
    const block = e.target.closest('.sb-block-absence')
    const startW = block.offsetWidth
    const startL = parseFloat(block.style.left)
    const SNAP_PX = pxPerHr.value / 4

    const snapPx = px => Math.round(px / SNAP_PX) * SNAP_PX

    function onMove (ev) {
      const dx = ev.clientX - startX
      if (side === 'right') {
        block.style.width = Math.max(SNAP_PX, snapPx(startW + dx)) + 'px'
      } else {
        const newL = snapPx(startL + dx)
        const newW = startW + (startL - newL)
        if (newW >= SNAP_PX && newL >= 0) {
          block.style.left = newL + 'px'
          block.style.width = newW + 'px'
        }
      }
      const curL = parseFloat(block.style.left)
      const curW = parseFloat(block.style.width)
      const sH = H_START.value + curL / pxPerHr.value
      const eH = sH + curW / pxPerHr.value
      const lbl = block.querySelector('.sb-absence-label')
      if (lbl) lbl.textContent = `${hToTime(sH)} → ${hToTime(eH)}`
    }

    function onUp () {
      document.removeEventListener('mousemove', onMove)
      document.removeEventListener('mouseup', onUp)
      const curL = parseFloat(block.style.left)
      const curW = parseFloat(block.style.width)
      const newStartH = H_START.value + curL / pxPerHr.value
      const newEndH = newStartH + curW / pxPerHr.value
      const startTime = hToTime(newStartH)
      const endTime = hToTime(newEndH)
      tech.absenceStartTime = startTime
      tech.absenceEndTime = endTime
      updateTech(tech.name || tech.id, {
        absence_start_time: startTime,
        absence_end_time: endTime,
      }).catch(() => {})
    }

    document.addEventListener('mousemove', onMove)
    document.addEventListener('mouseup', onUp)
  }

  return { startAbsenceResize }
}
