import React, {useState, useEffect} from "react";
import { View, Text, StyleSheet, Alert, TouchableOpacity, Image, StatusBar, Pressable } from "react-native";

import MapLibreGL from '@maplibre/maplibre-react-native';
import { MapView,ShapeSource,Camera,UserLocation,PointAnnotation,FillLayer,LineLayer,VectorSource } from "@maplibre/maplibre-react-native";
import Geolocation from "@react-native-community/geolocation";
import Modal from "react-native-modal";

type MapCollectLineProps = {route: any,navigation: any}
function MapCollectLineScreen({route,navigation}:MapCollectLineProps):React.JSX.Element{
    
    const apiKey = "JoJs2pcDv5o0yQlQLMfI";
    const [basemap, setBasemap] = useState("streets-v2");
    const styleURL = `https://api.maptiler.com/maps/${basemap}/style.json?key=${apiKey}`;

    
    const [currentPosition, setCurrentPosition] = useState<[number,number] | []>([]);
    const [currentPositionCamera, setCurrentPositionCamera] = useState<[number,number] | []>([0,0]);
    const [coordinates,setCoordinates] = useState<any>([
    ]);

    const [startPoint, setStartPoint] = useState<any>([]);
    const [manyPick, setManyPick] = useState(0);

    const morePoint = () => {
        setManyPick(manyPick+1);
        setStartPoint([...startPoint,`point${manyPick+1}`])
        setCoordinates([...coordinates,currentPosition])
    }

    const checkArrayCoord = (()=> {
        console.log("for Geojeson",coordinates[0])
    })


    const [reqCount, setReqCount] = useState(0);
    const [long,setLong] = useState(0);
    const [lat,setLat] = useState(0);
    const [accuracy,setAccuracy] = useState(0);
    const [timeStamp,setTimeStamp] = useState(0);
    const [modalBasemap,setmodalBasemap] = useState(false);
    const [modalLayerList,setmodalLayerList] = useState(false);
    

    useEffect(() => {
        const intervalID = setInterval(() => {
            Geolocation.getCurrentPosition(
                position => {
                    setReqCount((reqCount) => reqCount + 1)
                    setLong(position.coords.longitude);
                    setLat(position.coords.latitude);
                    setAccuracy(position.coords.accuracy);
                    setTimeStamp(position.timestamp);
                    setReqCount((reqCount) => reqCount++ );
                    setCurrentPosition([position.coords.longitude,position.coords.latitude])
                    setCurrentPositionCamera([position.coords.longitude,position.coords.latitude])
                    console.log("Long",position.coords.longitude);
                    console.log("Lat",position.coords.latitude);
                    console.log("current",[position.coords.longitude,position.coords.latitude]);
                    
                    
                },
                error => {
                    console.log('Error Getting current position', error);
                },
                {timeout:20000,enableHighAccuracy:false,maximumAge:0}
            );
            
            
            // setReqCount((reqCount) => (reqCount > 0 ? reqCount+1 : 10));
        }, 5000);
    
        return () => {
          clearInterval(intervalID);
        };
    }, []);

    const replacingCoordinate = (index:number,coor:any) => {
        const nextCoordinate  = coordinates.map((c:any,i:number) => {
            if (i === index){
                return c = coor
            } else {
                return c
            }
        });
        setCoordinates(nextCoordinate);
    }

    const [zoom, setZoom] = useState(15);
    const MAX_ZOOM_LEVEL = 20;
    const MIN_ZOOM_LEVEL = 5;

    const handleZoom = (isZoomIn = false) => {
        let currentZoomLevel = zoom;
        if (!isZoomIn && currentZoomLevel === MAX_ZOOM_LEVEL) {
        currentZoomLevel -= 1;
        }
        else if (isZoomIn && currentZoomLevel === MIN_ZOOM_LEVEL) {
        currentZoomLevel += 1;
        }
        if (
        currentZoomLevel >= MAX_ZOOM_LEVEL ||
        currentZoomLevel <= MIN_ZOOM_LEVEL
        ) {
        return;
        }
        currentZoomLevel = isZoomIn ? currentZoomLevel + 1 : currentZoomLevel - 1;
        setZoom(currentZoomLevel);
    }
    
    

    return(
        <View style={{flex:1}}>
            <StatusBar backgroundColor="#34A6F8" barStyle={'light-content'} />
            <View key={"mainBackground"} style={{backgroundColor:'#34A6F8',width:'100%',height:'100%'}} />
            
            <MapView
                style={{width:'100%',height:'100%',position:'absolute',marginTop:10,borderTopRightRadius:50,borderTopLeftRadius:35,overflow:'hidden'}}
                mapStyle={styleURL}
                zoomEnabled={true}
                onRegionDidChange={(region)=>
                    setZoom(region.properties.zoomLevel)
                }
                compassEnabled={false}
            >
                <Camera
                    key={"camera"}
                    centerCoordinate={currentPositionCamera}
                    zoomLevel={zoom}
                    minZoomLevel={5}
                    maxZoomLevel={20}
                />
                {coordinates.length > 1 ?
                    <ShapeSource
                        id="line"
                        shape={{
                            "type": "FeatureCollection",
                            "features": [
                                {
                                    "type": "Feature",
                                    "properties": {},
                                    "geometry": {
                                        "type": "LineString",
                                        "coordinates": coordinates
                                    }
                                }
                            ]
                        }}  
                    >
                        <LineLayer 
                            id="linelayer1"
                            style={{lineColor:'red',lineWidth:3}}
                        />
                    </ShapeSource>
                    :
                    null
                }
                <UserLocation
                    key={"userLoc"}
                    androidRenderMode='compass'
                    renderMode='native'
                    animated={true}
                    showsUserHeadingIndicator={true}
                    
                />
                {
                    startPoint.map((item:any,index:number)=>(
                        <PointAnnotation
                            children={<></>}
                            key={index}
                            id={item}
                            coordinate={coordinates[index]}
                            draggable={true}
                            onDrag={(e)=> {
                                replacingCoordinate(index,e.geometry.coordinates)

                                
                            }}
                        />
                    ))
                }
                

            </MapView>
            
            <TouchableOpacity onPress={()=>setmodalLayerList(true)} style={{position:'absolute',backgroundColor:'#FFFFFF',width:50,height:50,borderRadius:25,alignItems:'center',justifyContent:'center',top:'7%',left:'4%'}}>
                <Image
                      source={require('../../assets/icon/layerList.png')}
                    //   style={styles.buttonImageIconStyle}
                  />
            </TouchableOpacity>
            <TouchableOpacity onPress={()=>setmodalBasemap(true)} style={{position:'absolute',backgroundColor:'#FFFFFF',width:50,height:50,borderRadius:25,alignItems:'center',justifyContent:'center',top:'15%',left:'4%'}}>
                <Image
                      source={require('../../assets/icon/mapOutline.png')}
                    //   style={styles.buttonImageIconStyle}
                  />
            </TouchableOpacity>
            {/* <TouchableOpacity style={{position:'absolute',backgroundColor:'#FFFFFF',width:50,height:50,borderRadius:25,alignItems:'center',justifyContent:'center',top:'23%',left:'4%'}}>
                <Image
                      source={require('../../assets/icon/findmylock.png')}
                    //   style={styles.buttonImageIconStyle}
                  />
            </TouchableOpacity> */}
            

            <Modal isVisible={modalBasemap} animationIn={'fadeInUp'} animationOut={'fadeOutDown'} backdropOpacity={0} onBackdropPress={()=>setmodalBasemap(false)} style={{top:'18%',alignSelf:'center'}}>
                <View key={"modal container"} style={{width:330,height:333,backgroundColor:'#FFFFFF',borderRadius:25}}>
                    <View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between',paddingLeft:30,paddingTop:20,paddingRight:10}}>
                        <Text style={{fontSize:20,fontWeight:'semibold'}}>
                            Basemap Gallery
                        </Text>
                        <Pressable onPress={()=>setmodalBasemap(false)} style={{alignSelf:'flex-end',padding:10}}>
                            <Image
                                source={require('../../assets/icon/x.png')}
                            />
                        </Pressable>
                    </View>
                </View>
            </Modal>

            <Modal isVisible={modalLayerList} animationIn={'fadeInUp'} animationOut={'fadeOutDown'} backdropOpacity={0} onBackdropPress={()=>setmodalLayerList(false)} style={{top:'18%',alignSelf:'center'}}>
                <View key={"modal container"} style={{width:330,height:333,backgroundColor:'#FFFFFF',borderRadius:25}}>
                    <View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between',paddingLeft:30,paddingTop:20,paddingRight:10}}>
                        <Text style={{fontSize:20,fontWeight:'semibold'}}>
                            Layer List
                        </Text>
                        <Pressable onPress={()=>setmodalLayerList(false)} style={{alignSelf:'flex-end',padding:10}}>
                            <Image
                                source={require('../../assets/icon/x.png')}
                            />
                        </Pressable>
                    </View>
                </View>
            </Modal>

            {/* <View style={styles.gotoLocate}>
                <TouchableOpacity onPress={() => handleZoom(true)}>
                  <Image
                      source={require('../../assets/icon/plus.png')}
                      style={styles.buttonImageIconStyle}
                  />
                </TouchableOpacity>
                <TouchableOpacity onPress={() => handleZoom()}>
                  <Image
                      source={require('../../assets/icon/minus.png')}
                      style={styles.buttonImageIconStyle}
                  />
                </TouchableOpacity>
                <TouchableOpacity onPress={checkArrayCoord}>
                    <Image
                        source={require('../../assets/icon/MyLoc.png')}
                        style={styles.buttonImageIconStyle}
                    />
                </TouchableOpacity>
            </View> */}
            
            {
                startPoint.length === 0 ?
                    currentPosition.length > 0 ?
                    <TouchableOpacity style={{position:'absolute',alignSelf:'center',bottom:20}} onPress={morePoint}>
                        <View style={{backgroundColor:'#217dd3',flexDirection:'row',width:350,height:50,borderRadius:10,justifyContent:'center'}}>
                            <Text style={{alignSelf:'center',fontWeight:'bold',fontSize:20,color:'white'}}>Pick Start Point</Text>
                        </View>
                    </TouchableOpacity>
                    :
                    <TouchableOpacity disabled={true} style={{position:'absolute',alignSelf:'center',bottom:20}} onPress={morePoint}>
                        <View style={{backgroundColor:'#217dd3',flexDirection:'row',width:350,height:50,borderRadius:10,justifyContent:'center',opacity:0.5}}>
                            <Text style={{alignSelf:'center',fontWeight:'bold',fontSize:20,color:'white'}}>Pick Start Point</Text>
                        </View>
                    </TouchableOpacity>
                :
                    <View style={{position:'absolute',width:'100%',bottom:20,justifyContent:'center',alignItems:'center',flexDirection:'row'}}>
                        <TouchableOpacity style={{margin:10}} onPress={morePoint}>
                            <View style={{backgroundColor:'#2daee0',flexDirection:'row',width:60,height:60,borderRadius:100,justifyContent:'center'}}>
                            <Image
                                source={require('../../assets/icon/add.png')}
                                style={{width:40,height:40,justifyContent:'center',alignSelf:'center'}}
                            />
                            </View>
                        </TouchableOpacity>
                        {
                            startPoint.length > 1 ?
                            <TouchableOpacity style={{margin:10}} onPress={()=> {
                                navigation.navigate('PDAM Collecting', { screen: 'PDAM Collecting',coordinates: coordinates})
                            }}>
                                <View style={{backgroundColor:'#43eb34',flexDirection:'row',width:60,height:60,borderRadius:100,justifyContent:'center'}}>
                                <Image
                                    source={require('../../assets/icon/check.png')}
                                    style={{width:40,height:40,justifyContent:'center',alignSelf:'center'}}
                                />
                                </View>
                            </TouchableOpacity>
                            :
                            null
                        }
                        
                        
                    </View>
            }
        </View>
    )
}

const styles = StyleSheet.create({
    buttonImageIconStyle: {
        padding: 10,
        margin: 5,
        height: 25,
        width: 25,
        resizeMode: 'stretch',
      },
    gotoLocate: {
        opacity: 0.6,
        position: 'absolute',
        top:120,
        right: 5,
        borderRadius:8,
        paddingHorizontal:7,
        width: 50,
        // height: 50,
        backgroundColor: "white",
        flexDirection: 'column',
        gap: 10
      }
});

export default MapCollectLineScreen;
