import React, {useState, useEffect, useRef} from "react";
import { View, Text, StyleSheet, Alert, TouchableOpacity, Image } 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 {useNavigation,NavigationContainer,useIsFocused} from '@react-navigation/native';
import Geolocation from "@react-native-community/geolocation";
import turfcenter from '@turf/center';
const {points,polygon,lineString} =  require('@turf/helpers');

MapLibreGL.setAccessToken(null);
type MapViewPolygonProps = {route: any,navigation: any}



function MapViewPolygonScreen({route,navigation}:MapViewPolygonProps):React.JSX.Element{
    // console.log(route.params.data);
    const {data} = route.params
    console.log("a",data);
    
    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(data.geom);

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

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

    const checkArrayCoord = (()=> {
        console.log("for Geojeson",coordinates)
        console.log('first coordinate',coordinates[0]);
        console.log("manyPick",manyPick);
        console.log("lenght",coordinates.length);
    })
    
    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 isFocused = useIsFocused();
    const [onDrag,setOndrag] = useState(false);
    const [centerCoords,setCenterCoords] = useState<number[]>([]);
    useEffect(() => {
        if(isFocused){
            // console.log(data);
            coordinates.pop();
            let centCord = turfcenter(points(coordinates));
            console.log("center kedua",centCord);
            setCenterCoords(centCord.geometry.coordinates); 
        }
    }, [isFocused]);
    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(17);
    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}}>
            <MapView
                style={{alignSelf:'stretch',flex:1}} 
                mapStyle={styleURL}
                zoomEnabled={true}
                onRegionDidChange={(region)=>
                    setZoom(region.properties.zoomLevel)
                }
            >
                <Camera
                    key={"camera"}
                    centerCoordinate={centerCoords}
                    zoomLevel={zoom}
                    minZoomLevel={5}
                    maxZoomLevel={20}
                />
                <ShapeSource
                    id="polygon"
                    shape={{
                        "type": "FeatureCollection",
                        "features": [
                            {
                                "type": "Feature",
                                "properties": {},
                                "geometry": {
                                    "type": "Polygon",
                                    "coordinates": [
                                        coordinates
                                    ],
                                }
                            }
                        ]
                    }}  
                >
                    <LineLayer 
                        id="linelayer1"
                        style={{lineColor:'red',lineWidth:1}}
                    />
                    <FillLayer 
                        id="some-fill-feature"
                        style={{
                            fillColor: ['interpolate', ['linear'], ['zoom'], 0, '#eeddbb', 2, '#0daa00', 3, '#bbbbee'],
                            fillOpacity:0.5
                        }}
                    />
                </ShapeSource>
                
                <UserLocation
                    key={"userLoc"}
                    androidRenderMode='compass'
                    renderMode='native'
                    animated={true}
                    showsUserHeadingIndicator={true}
                />
                {
                    coordinates.map((item:any,index:any)=>(
                        <PointAnnotation
                            children={<></>}
                            key={index}
                            id={String(index)}
                            coordinate={item}
                            draggable={true}
                            onDrag={(e)=> {
                                setOndrag(true)
                                replacingCoordinate(index,e.geometry.coordinates)
                            }}
                        />
                    ))
                }
            </MapView>

            {/* Widget Map */}
            <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>
            {
                onDrag ?
                <View style={{position:'absolute',width:'100%',bottom:20,justifyContent:'center',alignItems:'center',flexDirection:'row'}}>
                    <TouchableOpacity style={{margin:10}} onPress={()=> {
                        setCoordinates([])
                        setCoordinates(data.geom)

                        // setStartPoint([])
                        // setManyPick(0)
                        
                    }}>
                        <View style={{backgroundColor:'#a8a59b',flexDirection:'row',width:60,height:60,borderRadius:100,justifyContent:'center'}}>
                        <Image
                            source={require('../../assets/icon/reset.png')}
                            style={{width:40,height:40,justifyContent:'center',alignSelf:'center'}}
                        />
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity style={{margin:10}} onPress={()=> {
                        // checkArrayCoord()
                        // 
                        navigation.navigate('Permit Editing',{ screen: 'Edit',data: {
                            id:data.id,
                            company_name:data.company_name,
                            permit_status:data.permit_status,
                            location:data.location
                        }, coors:coordinates })
                        // if(drawingComplete){
                        //     Alert.alert("goto");
                            
                        // }
                        
                    }}>
                        <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>
                </View>
                :
                null
                // <View style={{position:'absolute',width:'100%',bottom:20,justifyContent:'center',alignItems:'center',flexDirection:'row'}}>
                //     <TouchableOpacity disabled={true} style={{margin:10}} onPress={()=> {
                //         setCoordinates([])
                //         setStartPoint([])
                //         setManyPick(0)
                        
                //     }}>
                //         <View style={{backgroundColor:'#a8a59b',flexDirection:'row',width:60,height:60,borderRadius:100,justifyContent:'center',opacity:0.5}}>
                //         <Image
                //             source={require('../../assets/icon/reset.png')}
                //             style={{width:40,height:40,justifyContent:'center',alignSelf:'center'}}
                //         />
                //         </View>
                //     </TouchableOpacity>
                //     <TouchableOpacity disabled={true} style={{margin:10}} onPress={()=> {
                //         // checkArrayCoord()
                //         navigation.navigate('Permit Collecting', { screen: 'Permit Collecting',coordinates: coordinates})
                //         // if(drawingComplete){
                //         //     Alert.alert("goto");
                            
                //         // }
                        
                //     }}>
                //         <View style={{backgroundColor:'#43eb34',flexDirection:'row',width:60,height:60,borderRadius:100,justifyContent:'center',opacity:0.5}}>
                //         <Image
                //             source={require('../../assets/icon/check.png')}
                //             style={{width:40,height:40,justifyContent:'center',alignSelf:'center'}}
                //         />
                //         </View>
                //     </TouchableOpacity>
                // </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 MapViewPolygonScreen;
