import { useEffect, useState } from 'react'
import { Maximize2, Minimize2 } from 'lucide-react'

import './FullscreenControl.scss'

type FullscreenControlProps = {
  targetId: string
}

export function FullscreenControl({ targetId }: FullscreenControlProps) {
  const [isFullscreen, setIsFullscreen] = useState(false)

  useEffect(() => {
    function handleFullscreenChange() {
      const element = document.getElementById(targetId)

      setIsFullscreen(Boolean(element && document.fullscreenElement === element))
    }

    document.addEventListener('fullscreenchange', handleFullscreenChange)

    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange)
    }
  }, [targetId])

  async function handleToggleFullscreen() {
    const element = document.getElementById(targetId)

    if (!element) return

    if (document.fullscreenElement === element) {
      await document.exitFullscreen()
      return
    }

    if (document.fullscreenElement) {
      await document.exitFullscreen()
    }

    await element.requestFullscreen()
  }

  return (
    <button
      className="map-fullscreen-button"
      type="button"
      onClick={handleToggleFullscreen}
      aria-label={
        isFullscreen
          ? 'Выйти из полноэкранного режима'
          : 'Открыть карту на весь экран'
      }
      title={
        isFullscreen
          ? 'Выйти из полноэкранного режима'
          : 'Открыть карту на весь экран'
      }
    >
      {isFullscreen ? <Minimize2 size={18} /> : <Maximize2 size={18} />}
    </button>
  )
}
