// withHooks
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';


import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { MarketButton } from 'esoftplay/cache/market/button/import';
import { MarketGps } from 'esoftplay/cache/market/gps/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketInput_square } from 'esoftplay/cache/market/input_square/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';

import React, { useEffect, useRef } from 'react';
import { ActivityIndicator, Pressable, Text, TouchableOpacity, View } from 'react-native';
import MapView from 'react-native-maps';


export interface MarketMapProps {

}
export default function m(props: MarketMapProps): any {
  const _senderKey = LibNavigation.getArgs(props, "_senderKey")
  const ll = LibNavigation.getArgs(props, "latlong")
  const ref = useRef<MapView>(null)
  const coordinatePanel = useRef<LibSlidingup>(null)
  let textCoordinate = useRef('').current
  const [region, setRegion] = useSafeState<any>()
  const [initregion, setInitRegion, getRegion] = useSafeState<any>()
  const [layout, setLayout] = useSafeState<any>()
  const [loading, setLoading] = useSafeState(false)

  function focusOnMe() {
    setLoading(true)
    new MarketGps().getLocationAsync().then((v) => {
      if (v?.coords?.latitude && v?.coords?.longitude) {
        const { coords: { latitude, longitude } } = v
        ref.current?.animateToRegion?.({ ...getRegion(), latitude, longitude }, 300)
      }
      setLoading(false)
    }).catch(() => {
      LibToastProperty.show(esp.lang("market/map", "location_notfound"))
      setLoading(false)
    })
  }

  useEffect(() => {
    if (ll && ll.includes(",")) {
      setInitRegion({
        latitude: Number(ll.split(",")[0]),
        longitude: Number(ll.split(",")[1]),
        latitudeDelta: 0.002,
        longitudeDelta: 0.002,
      })
    } else
      new MarketGps().getLocationAsync().then((s) => {
        setInitRegion({
          latitude: Number(s?.coords?.latitude),
          longitude: Number(s?.coords?.longitude),
          latitudeDelta: 0.002,
          longitudeDelta: 0.002,
        })
      })
    return () => LibNavigation.cancelBackResult(_senderKey)
  }, [])

  return (
    <View style={{ flex: 1, backgroundColor: "white" }} >
      <MarketHeader
        rightIcon={{ name: 'map-marker-plus-outline', onPress: () => { coordinatePanel?.current?.show?.() } }}
        leftIcon={{ name: "close", onPress: () => { LibNavigation.back() } }} title={esp.lang("market/map", "header_title")} />
      {
        !initregion ? <LibLoading />
          :
          <>
            <View style={{ flex: 1 }} onLayout={(x) => setLayout(x.nativeEvent.layout)} >
              <MapView
                ref={ref}
                initialRegion={initregion}
                showsScale
                loadingEnabled
                provider="google"
                showsTraffic
                zoomControlEnabled
                showsCompass
                showsUserLocation
                zoomEnabled
                onRegionChangeComplete={(r) => { setRegion(r) }}
                style={{ flex: 1 }} >
              </MapView>
              {layout && <LibPicture
                source={esp.assets('market/ic_pin.png')}
                style={{ height: 30, width: 12, position: "absolute", top: (layout.height * 0.5) - 28, left: (layout.width * 0.5) - 6 }} />}

              <View style={{ position: 'absolute', right: 10, top: 10, left: 10, flexDirection: "row", alignItems: "center" }}>
                <Pressable onPress={() => {
                  LibNavigation.navigateForResult("market/address_autocomplete", undefined, 99283).then((c) => {
                    const [latitude, longitude] = c.latlong.split(",").map((x: string) => parseFloat(x))
                    if (ref.current) {
                      ref.current?.animateToRegion?.({ latitude, longitude, latitudeDelta: 0.005, longitudeDelta: 0.005, }, 500)
                    }
                  })
                }} style={{ backgroundColor: "white", borderWidth: 1, borderColor: '#e6e6e6', height: 45, borderRadius: 13, marginRight: 10, justifyContent: 'center', flex: 1, paddingHorizontal: 10 }}>
                  <Text>{esp.lang("market/map", "find_location")}</Text>
                </Pressable>
                <TouchableOpacity
                  disabled={loading}
                  onPress={() => focusOnMe()}
                  style={{ backgroundColor: 'white', borderWidth: 1, borderColor: '#f1f1f1', borderRadius: 13, height: 45, width: 45, alignItems: "center", justifyContent: "center" }} >
                  {loading ? <ActivityIndicator color={MarketStyle.colorPrimaryMarket} size={'small'} /> : <LibIcon name={'crosshairs-gps'} />}
                </TouchableOpacity>
              </View>
            </View>
            <View style={{ paddingHorizontal: 17, marginTop: 4, marginBottom: 8 }} >
              <MarketButton text={esp.lang("market/map", "btn_save")} onPress={() => {
                LibProgress.show(esp.lang("market/map", "text_wait"))
                new MarketGps().reverseGeocoding(region?.latitude + "," + region?.longitude).then((x) => {
                  let latlong = !!region?.latitude ? region?.latitude + "," + region?.longitude : initregion.latitude + "," + initregion.longitude
                  LibProgress.hide()
                  LibNavigation.sendBackResult({ latlong: latlong, name: x }, _senderKey)
                })
              }} />
            </View>
            <LibSlidingup ref={coordinatePanel} >
              <View style={{ backgroundColor: 'white', borderTopLeftRadius: 30, borderTopRightRadius: 30, borderWidth: 1, borderColor: '#f1f2f3', padding: 20 }} >
                <LibTextstyle text={esp.lang("market/map", "label_input_coordinat")} textStyle={"body"} style={{ textAlign: 'center', marginBottom: 20 }} />
                <MarketInput_square placeholder={'-6.812033,110.8187763'} onChangeText={(t) => { textCoordinate = t }} />
                <View style={{ paddingHorizontal: 17, marginTop: 4, marginBottom: 8 }} >
                  <MarketButton text={esp.lang("market/map", "btn_pin")} onPress={() => {
                    if (
                      textCoordinate.split(',').length == 2
                      && !isNaN(Number(textCoordinate.split(',')[0]))
                      && !isNaN(Number(textCoordinate.split(',')[1]))
                    ) {
                      ref.current?.animateToRegion?.({ ...region, latitude: Number(textCoordinate.split(',')[0]), longitude: Number(textCoordinate.split(',')[1]) }, 300)
                      coordinatePanel?.current?.hide()
                    }
                    else
                      LibToastProperty.show(esp.lang("market/map", "coordinate_not_valid"))
                  }} />
                </View>
              </View>
            </LibSlidingup>
          </>
      }
    </View>
  )
}