import 'tippy.js/dist/tippy.css'

import Tippy from '@tippyjs/react'
import axios from 'axios'
import Image from 'next/image'
import React, { useEffect, useState } from 'react'
import { Fade } from 'react-awesome-reveal'

const ImagePin = () => {
  const [data, setData] = useState(null)
  const [delayHandler, setDelayHandler] = useState(null)
  const [actv, setActv] = useState(null)
  const [page, setPage] = useState(null)

  useEffect(() => {
    const fetchData = async () => {
      let maps = await axios.get('/api/map')
      console.log(maps)
      maps = maps.data.map(function (r) {
        let d = {}
        let ct = r.page.content
        d['kode'] = r.kode
        d['cordX'] = r.cordX
        d['cordY'] = r.cordY
        d['title'] = r.page.title
        d['slug'] = r.page.slug
        d['content'] = (function (x) {
          let dt = []
          ;(function deep(v, l) {
            for (let i = 0; i < l; i++) {
              Object.keys(v[i]).forEach(function (f) {
                if (f == 'children') {
                  deep(v[i][f], v[i][f].length)
                } else if (f == 'text') {
                  dt.push(v[i][f])
                }
              })
            }
          })(x, x.length)

          return dt
        })(ct)
        return d
      })
      console.log(maps)
      setData(maps)
    }

    if (data === null) {
      fetchData()
    }
  }, [data])

  function open(e) {
    var t = e.target
    if (t.className.indexOf('pin-b') == -1) {
      t = e.target.parentNode
    }
    console.log(t)
  }

  function EventPoinEnter(event) {
    var cod = event.target.dataset.kodePc
    var poin = document.querySelector<HTMLElement>(
      "div[data-point='" + cod + "']"
    )
    var df = document.querySelector<HTMLElement>("div[data-open='" + cod + "']")
    df.style.display = 'block'
    var y = poin.getBoundingClientRect()
    var px = Math.round((y.left / window.innerWidth) * 100)
    if (px < 0) {
      px = px * -1
    }
    console.log(px)
    if (px < 40) {
      df.style.right = 'auto'
      df.style.left = '0px'
    } else if (px >= 40 && px <= 70) {
      df.style.right = '-180px'
      df.style.left = 'auto'
    } else if (px > 70) {
      df.style.right = '0px'
      df.style.left = 'auto'
    }

    if (actv != null && actv != event.target.dataset.kodePc) {
      var f = document.querySelector<HTMLElement>(
        "div[data-open='" + actv + "']"
      )
      f.style.display = 'none'
      setActv(cod)
    } else {
      setActv(cod)
    }
    clearTimeout(delayHandler)
  }

  function EventPointerLeave(event) {
    var cod = event.target.dataset.kodePc
    setDelayHandler(
      setTimeout(() => {
        document.querySelector<HTMLElement>(
          "div[data-open='" + cod + "']"
        ).style.display = 'none'
      }, 500)
    )
  }

  return (
    <div className="m-auto py-10">
      <div className="flex items-center justify-center text-center">
        <div className="relative inline-block">
          <Image
            src="https://cdn.sanity.io/images/helyis1v/production/cff6f479f3197dc3ec6780bb09e433ec4c7229be-805x676.png"
            width={800}
            height={600}
            alt="GWK Cultural Park Map"
            className="intermap"
          />
          {/* <CldImage
            src="https://cdn.sanity.io/images/helyis1v/production/cff6f479f3197dc3ec6780bb09e433ec4c7229be-805x676.png"
            width={800}
            height={600}
            alt="GWK Cultural Park Map"
            className="intermap"
          /> */}
          {(function () {
            if (Array.isArray(data)) {
              return data.map((s, i) => (
                <div
                  key={i}
                  style={{ left: s.cordX + '%', top: s.cordY + '%' }}
                  className="absolute "
                >
                  <span
                    style={{
                      display: 'inline-block',
                      outline: 'none',
                      background: '#ddd',
                      width: '25px',
                      marginBottom: '5px',
                      marginLeft: '-5px',
                      borderRadius: '10px',
                      fontWeight: 'bold',
                      border: '2px solid #333',
                    }}
                  >
                    {s.kode}
                  </span>
                  <div className="relative">
                    <div
                      data-slug={s.slug}
                      data-kode-pc={i}
                      data-point={i}
                      onMouseLeave={EventPointerLeave}
                      onPointerEnter={EventPoinEnter}
                      key={i}
                      onClick={open}
                      className="pin-b absolute flex min-h-[15px] min-w-[15px] animate-pulse cursor-pointer items-center justify-center rounded-[50%] bg-black shadow-white transition duration-300 ease-in-out hover:scale-150 hover:animate-ping"
                    >
                      <div
                        data-kode-pc={i}
                        className="min-h-[5px] min-w-[5px] rounded bg-white"
                      ></div>
                    </div>
                    <div
                      data-slug={s.slug}
                      data-open={i}
                      data-kode-pc={i}
                      onMouseLeave={EventPointerLeave}
                      onPointerEnter={EventPoinEnter}
                      style={{ display: 'none', zIndex: 99 }}
                      className="modal-show absolute right-[-20px] top-[30px] min-w-[350px] max-w-[350px] animate-fade-up rounded bg-white p-5 text-left shadow-md animate-duration-500 animate-once"
                    >
                      <div data-kode-pc={i} className="mb-2 border-b-2">
                        <h2 className="heading-h2-medium mb-2 text-2xl font-semibold text-yellow-600 sm:text-3xl">
                          {s.title}
                        </h2>
                      </div>
                      <div data-kode-pc={i}>
                        <div data-kode-pc={i} className="font-sans text-base">
                          {(function (sr) {
                            if (sr.content.length > 0) {
                              return sr.content.map((r, i) => (
                                <p key={i}>{r}</p>
                              ))
                            }
                            return <></>
                          })(s)}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              ))
            } else {
              return <></>
            }
          })()}
        </div>
      </div>
    </div>
  )
}

export default ImagePin
