"use client"

import type React from "react"
import { useCallback, useMemo, useState, useRef, useEffect } from "react"
import { Polyline } from "@react-google-maps/api"
import { Popover, Typography } from "@mui/material"
import type { LatLng } from "@/shared/types/Maps"
import { StatusColor } from "@/shared/sections/chauffeur/planingChauffeur/utils/schedule-utils"

interface MapPolylineDriverProps {
  path: LatLng[]
  color: string
  index: number
  emptyKm?: number
}

export const MapPolylineDriver: React.FC<MapPolylineDriverProps> = ({ path, color, index, emptyKm = 20 }) => {
  const [anchorPosition, setAnchorPosition] = useState<{ top: number; left: number } | null>(null)
  const [isPopoverOpen, setIsPopoverOpen] = useState(false)
  const isHoveringRef = useRef(false)

  useEffect(() => {
    if (color !== StatusColor.GREY) return

    const handleGlobalMouseMove = (e: MouseEvent) => {
      if (isHoveringRef.current) {
        setAnchorPosition({
          top: e.clientY + 15,
          left: e.clientX + 15,
        })
      }
    }
    window.addEventListener("mousemove", handleGlobalMouseMove)

    return () => {
      window.removeEventListener("mousemove", handleGlobalMouseMove)
    }
  }, [color])

  const handlePolylineMouseOver = useCallback(() => {
    if (color === StatusColor.GREY) {
      isHoveringRef.current = true

      requestAnimationFrame(() => {
        if (isHoveringRef.current) {
          setIsPopoverOpen(true)
        }
      })
    }
  }, [color])

  const handlePolylineMouseOut = useCallback(() => {
    isHoveringRef.current = false

    setTimeout(() => {
      if (!isHoveringRef.current) {
        setIsPopoverOpen(false)
      }
    }, 300)
  }, [])

  const lineSymbol = useMemo(
    () => ({
      path: "M 0,-1 0,1",
      strokeOpacity: 1,
      scale: 4,
    }),
    [],
  )

  const polylineOptions: google.maps.PolylineOptions = {
    strokeColor: color,
    strokeWeight: 3,
    clickable: true,
    strokeOpacity: index === 1 ? 0 : 1,
    ...(index === 1 && {
      icons: [
        {
          icon: lineSymbol,
          offset: "0",
          repeat: "20px",
        },
      ],
    }),
  }

  return (
    <>
      <Polyline
        path={path}
        options={polylineOptions}
        onMouseOver={handlePolylineMouseOver}
        onMouseOut={handlePolylineMouseOut}
      />

      {color === StatusColor.GREY ? (
        <Popover
          open={isPopoverOpen}
          anchorReference="anchorPosition"
          anchorPosition={anchorPosition || undefined}
          sx={{pointerEvents: "none"}}
          onClose={() => {
            isHoveringRef.current = false
            setIsPopoverOpen(false)
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
          slotProps={{
            paper: {
              sx: {
                borderRadius: 2,
                p: 1,
                backgroundColor: "white",
                zIndex: 9999,
              },
            },
          }}
          disableRestoreFocus
        >
          <Typography
            sx={{
              fontSize: "0.875rem",
              color: "primary.main",
              fontWeight: (theme) => theme.typography.fontWeightMedium,
              whiteSpace: "nowrap",
            }}
          >
            km à vide = {`${emptyKm} km`}
          </Typography>
        </Popover>
      ):<></>}
    </>
  )
}

