import { ref } from 'vue'

export default function useImagePreview() {
  const show = ref(false)
  const div = document.createElement('div')
  div.style.position = 'fixed'
  div.style.zIndex = '9999999999999'
  div.style.display = 'none'
  const img = document.createElement('img')
  img.style.width = '300px'
  div.appendChild(img)
  document.body.appendChild(div)

  let currentTarget: HTMLElement | null = null

  const mousemoveHandler = (ev: MouseEvent) => {
    if (!currentTarget) return
    const rect = currentTarget.getBoundingClientRect()
    const inOrigin =
      ev.clientX >= rect.left &&
      ev.clientX <= rect.right &&
      ev.clientY >= rect.top &&
      ev.clientY <= rect.bottom

    const divRect = div.getBoundingClientRect()
    const inPreview =
      ev.clientX >= divRect.left &&
      ev.clientX <= divRect.right &&
      ev.clientY >= divRect.top &&
      ev.clientY <= divRect.bottom

    if (!inOrigin && !inPreview) {
      div.style.display = 'none'
      show.value = false
      window.removeEventListener('mousemove', mousemoveHandler)
      currentTarget = null
    }
  }

  const mouseoverImg = (ev: MouseEvent, url: string) => {
    ev.preventDefault()
    if (show.value === true) return
    img.src = url
    img.style.backgroundColor = '#eee'
    const cW = document.body.clientWidth
    const cH = document.body.clientHeight
    const cX = ev.clientX
    const cY = ev.clientY
    let x: number, y: number
    if (cY + 150 >= cH) y = cY - 300
    else y = cY - 150
    if (cX + 300 >= cW) x = cX - 300
    else x = cX + 60
    img.onload = () => {
      div.style.left = x + 'px'
      div.style.top = y + 'px'
      div.style.display = 'block'
      show.value = true
      currentTarget = ev.currentTarget as HTMLElement
      window.addEventListener('mousemove', mousemoveHandler)
    }
  }

  const mouseleaveImg = () => {
    if (show.value === false) return
    div.style.display = 'none'
    show.value = false
  }

  return { mouseoverImg, mouseleaveImg }
}
