"use client"

import { useMap } from "@vis.gl/react-google-maps"
import { useState } from "react"
import { useIntl } from "react-intl"

import PoiMarker from "@/components/Maps/Markers/Poi"
import Button from "@/components/TempDesignSystem/Button"
import Body from "@/components/TempDesignSystem/Text/Body"
import Title from "@/components/TempDesignSystem/Text/Title"

import styles from "./sidebar.module.css"

import type { SidebarProps } from "@/types/components/hotelPage/map/sidebar"
import type { Coordinates } from "@/types/components/maps/coordinates"

export default function Sidebar({
  activePoi,
  hotelName,
  pointsOfInterest,
  onActivePoiChange,
  coordinates,
}: SidebarProps) {
  const intl = useIntl()
  const map = useMap()
  const [isFullScreenSidebar, setIsFullScreenSidebar] = useState(false)
  const [isClicking, setIsClicking] = useState(false)
  const poiGroups = new Set(pointsOfInterest.map(({ group }) => group))
  const poisInGroups = Array.from(poiGroups).map((group) => ({
    group,
    pois: pointsOfInterest.filter((poi) => poi.group === group),
  }))

  function toggleFullScreenSidebar() {
    setIsFullScreenSidebar((prev) => !prev)
  }

  function moveToPoi(poiCoordinates: Coordinates) {
    if (map) {
      const hotelLatLng = new google.maps.LatLng(
        coordinates.lat,
        coordinates.lng
      )
      const poiLatLng = new google.maps.LatLng(
        poiCoordinates.lat,
        poiCoordinates.lng
      )

      const bounds = new google.maps.LatLngBounds()
      bounds.extend(hotelLatLng)
      bounds.extend(poiLatLng)

      map.fitBounds(bounds)

      const currentZoomLevel = map.getZoom()

      if (currentZoomLevel) {
        map.setZoom(currentZoomLevel - 1)
      }
    }
  }

  function handleMouseEnter(poiName: string) {
    if (!isClicking) {
      onActivePoiChange(poiName)
    }
  }

  function handlePoiClick(poiName: string, poiCoordinates: Coordinates) {
    setIsClicking(true)
    toggleFullScreenSidebar()
    onActivePoiChange(poiName)
    moveToPoi(poiCoordinates)
    setTimeout(() => {
      setIsClicking(false)
    }, 200)
  }

  return (
    <>
      <aside
        className={`${styles.sidebar} ${
          isFullScreenSidebar ? styles.fullscreen : ""
        }`}
      >
        <Button
          theme="base"
          intent="text"
          fullWidth
          className={styles.sidebarToggle}
          onClick={toggleFullScreenSidebar}
        >
          <Body textTransform="bold" color="textMediumContrast" asChild>
            <span>
              {intl.formatMessage({
                id: isFullScreenSidebar ? "View as map" : "View as list",
              })}
            </span>
          </Body>
        </Button>
        <div className={styles.sidebarContent}>
          <Title as="h4" level="h2" textTransform="regular">
            {intl.formatMessage(
              { id: "Things nearby HOTEL_NAME" },
              { hotelName }
            )}
          </Title>

          {poisInGroups.map(({ group, pois }) =>
            pois.length ? (
              <div key={group} className={styles.poiGroup}>
                <Body
                  color="black"
                  textTransform="bold"
                  className={styles.poiHeading}
                  asChild
                >
                  <h3>
                    <PoiMarker group={group} />
                    {intl.formatMessage({ id: group })}
                  </h3>
                </Body>
                <ul className={styles.poiList}>
                  {pois.map((poi) => (
                    <li key={poi.name} className={styles.poiItem}>
                      <button
                        className={`${styles.poiButton} ${activePoi === poi.name ? styles.active : ""}`}
                        onMouseEnter={() => handleMouseEnter(poi.name)}
                        onClick={() =>
                          handlePoiClick(poi.name, poi.coordinates)
                        }
                      >
                        <span>{poi.name}</span>
                        <span>{poi.distance} km</span>
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            ) : null
          )}
        </div>
      </aside>
      <div className={styles.backdrop} onClick={toggleFullScreenSidebar} />
    </>
  )
}
