"use client"

import {AutocompletePrediction, IDecodedAddress, useMapAutoComplete} from "@fanam-pkg/core-utils"
import {useState} from "react"
import {assets} from "../../assets"
import {Button, ImageView, TextField} from "../../atoms"
import {usePopup} from "../../hooks"
import {MapView} from "../../organisms"
import {MapViewProps, FormValueType} from "../../props"
import styles from "./styles.module.sass"

export const MapAutoComplete = ({decodedAddress, onConfirm}: MapViewProps) => {
  const {togglePopup} = usePopup()
  const [locationError, setLocationError] = useState("")
  const {predictions, searchText, fetchCurrentLocation, onClickPlace, onChangeSearch} =
    useMapAutoComplete(decodedAddress)

  const onConfirmAddress = (address: IDecodedAddress) => {
    onConfirm(address)
    togglePopup()
  }

  const showPopup = (locationData: IDecodedAddress | null) => {
    if (locationData)
      togglePopup({
        heading: "Confirm Location",
        children: <MapView decodedAddress={locationData} onConfirm={onConfirmAddress} />,
      })
  }

  const renderLocation = (item: AutocompletePrediction) => {
    const {place_id, description, structured_formatting} = item

    return (
      <li className={`${styles.address_detail} flex`} key={place_id} onClick={onClickPlace.bind(null, item, showPopup)}>
        <ImageView src={assets.ic_location} alt="location" imgSize={20} />
        <section className={`${styles.location_details} flex-col`}>
          <h5 className="bold ellipsis">{structured_formatting.main_text}</h5>
          <h6 className={`${styles.address_location} ellipsis`}>{description}</h6>
        </section>
      </li>
    )
  }

  const onSelectCurrentLocation = async () => {
    const result = await navigator.permissions.query({name: "geolocation"})
    if (result.state !== "denied") fetchCurrentLocation(showPopup)
    else setLocationError("Please enable location")
  }

  const onChangeData = (value: FormValueType) => onChangeSearch(value as string)

  return (
    <section className={styles.map_container}>
      <TextField
        value={searchText}
        onChangeData={onChangeData}
        placeholder="Search for a nearby location..."
        className={styles.input_container}
        label="Search Location"
      />
      <Button
        wrapperClass={styles.location_header}
        onClick={onSelectCurrentLocation}
        leadingIcon={assets.ic_cross_hair}
        buttonType="primary-outlined">
        Use Your Current Location
      </Button>
      {locationError ? locationError : null}
      {predictions.map(renderLocation)}
    </section>
  )
}
