import React, { useEffect, useState } from 'react';
import { Alert, Button, Dimensions, Image, Modal, Pressable, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';

// Depedency //

import {NavigationContainer} from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Geolocation from '@react-native-community/geolocation';
import Modal2 from "react-native-modal";
const Stack = createNativeStackNavigator();

// All Component //
import {AuthProvider, useAuth} from './src/component/authContext'; 
import MapCollectScreen from './src/component/mapCollectScreen';
import MainScreen from './src/component/mainscreen';
import CollectScreen from './src/component/collectscreen';
import SendListScreen from './src/component/sentscreen';
import SentListPJU from './src/component/sentPJU';
import SentListPDAM from './src/component/sentPDAM';
import SentListPermit from './src/component/sentPermit';
import InboxListScreen from './src/component/inboxscreen';
import InboxPJU from './src/component/inboxPJU';
import InboxPDAM from './src/component/inboxPDAM';
import InboxPermit from './src/component/inboxPermit';
import MapViewScreen from './src/component/mapviewscreen';
import EditScreen from './src/component/editscreen';
import LoginScreen from './src/component/loginscreen';
import HomeScreen from './src/component/homescreen';
import SurveyPage from './src/component/surveyPage';
import SurveyPJU from './src/component/surveyPJU';
import SurveyPDAM from './src/component/surveyPDAM';
import SurveyPermit from './src/component/surveyPERMIT';
import DraftListScreen from './src/component/draftscreen';
import DraftPJU from './src/component/draftPJU';
import DraftPDAM from './src/component/draftPDAM';
import DraftPermit from './src/component/draftPermit';
import ProfileScreen  from './src/component/profilescreen';
import MapCollectLineScreen from './src/component/mapCollectLineScreen';
import CollectLineScreen from './src/component/collectLinescreen';
import EditLineScreen from './src/component/editLinescreen';
import MapCollectPolygonScreen from './src/component/mapCollectPolygonScreen';
import CollectPolygonScreen from './src/component/collectPolygonscreen';
import EditPolygonScreen from './src/component/editPolygonscreen';
import MapViewPolygonScreen from './src/component/mapViewPolygonScreen';
import MapViewLineScreen from './src/component/mapViewLineScreen';
import SettingScreen from './src/component/settingScreen';
import MyAccount from './src/component/myAccount';
import ChangePass from './src/component/changePassword';
import { USER_API_URL } from "../SurveyApp/urlConfig";
import { PermissionsAndroid } from 'react-native';


function App(navigation:any) {
  return (
    <AuthProvider>
      <Nav/>
    </AuthProvider>
  );
};
export const Nav = () => {
  const { authState, onLogout} = useAuth();
  const [email,setEmail] = useState("");
  const [name,setName] = useState("");
  const [password, setPassword] = useState("");
  const [confirmpassword, setConfirmPassword] = useState("");
  const [modalVisibleProfil, setmodalVisibleProfil] = useState(false);
  const [validPass,setValidPass] = useState(false);
  const [emailExist,setEmailExist] = useState(false);
  const [currentPosition, setCurrentPosition] = useState<[number,number] | null>(null);
  const [modalVisible, setModalVisible] = useState(true);

  let width = Dimensions.get('window').width;
  let height = Dimensions.get('window').height;
  const [widthModal, setWidthModal] = useState(
    width < height ? '80%' : '50%',
  );
  const [heightModal, setHeightModal] = useState(
    width < height ? '60%' : '100%',
  );
  const [profileMarginModal, setProfileMarginModal] = useState(
    width < height ? 80 : 30,
  );
  const changeProfile = async () => {
    console.log({
      pass:password,
      confirm:confirmpassword,
      email:email===""?authState?.email:email
    });
    
    if(password!=""){
      if(password != confirmpassword) {
        setValidPass(true)
      }
      else{
        let updateProf = await fetch(`${USER_API_URL}/changePass`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          
          body: JSON.stringify({password:confirmpassword,id:authState?.id})
        });
        const status = updateProf.status
        if (status == 201) {
          Alert.alert('Change Password Success', 'You Must Re-Login!',[
            {
              text: 'Ok',
              onPress: onLogout
            }
          ])
        }
        else {
          Alert.alert("Internal Server Error")
        }
        
        setValidPass(false)
      }
    }
    let resultcheckExist = await fetch(`${USER_API_URL}/checkExist`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        
        body: JSON.stringify({email:email===""?authState?.email:email})
    });
    const checkExist = await resultcheckExist.json();
    if (checkExist.msg == "Not Use"){
      setEmailExist(false);
      let updateProf = await fetch(`${USER_API_URL}/update`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        
        body: JSON.stringify({email:email===""?authState?.email:email,name:name===""?authState?.name:name,id:authState?.id})
      });
      const status = updateProf.status
      if (status == 201) {
        Alert.alert('Change Profile Success', 'You Must Re-Login!',[
          {
            text: 'Ok',
            onPress: onLogout
          }
        ])
      }
      else {
        Alert.alert("Internal Server Error")
      }
    }
    else{
      setEmailExist(true);
    }
  };
  const requestCameraPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: 'Cool Photo App Camera Permission',
          message: 'Cool Photo App needs access to your camera so you can take awesome pictures.',
          buttonPositive: 'Ok'
        }
      )
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can use the camera")
      } else {
        console.log("Camera permission denied")
      }
    } catch (error) {
      
    }
  };
  useEffect(() => {
    requestCameraPermission()
    Dimensions.addEventListener('change', ({window:{width,height}})=>{
      if (width<height) {
        console.log('PORTRAIT');
        
        setWidthModal("80%")
        setHeightModal("60%")
        setProfileMarginModal(80)
      } else {
        setWidthModal("50%")
        setHeightModal("100%")
        setProfileMarginModal(30)
        console.log('LANDSCAPE');
      }
    })
  }, []);
  const logout = () => {
    onLogout();
    setmodalVisibleProfil(false);
  };
  const profileLayout = () => {
    return(<>
      <TouchableOpacity onPress={()=>setmodalVisibleProfil(true)}>
        <View style={{backgroundColor:'white',height:45,width:45,alignItems:'center',justifyContent:'center',borderRadius:100}}>
          <Image
            source={require('../SurveyApp/assets/icon/profile.png')}
            style={{height: 40,
              width: 40,
              resizeMode: 'stretch',}}
          />
        </View>
      </TouchableOpacity>
      <Modal2 
        isVisible={modalVisibleProfil}
        animationIn={'fadeIn'}
        animationOut={'slideOutUp'}
        animationOutTiming={600}
        >
        <View style={{flex: 1,alignItems:'center'}}>
            <View style={{
              alignSelf:'center',
              width:widthModal,
              height:heightModal,
              backgroundColor:'#e8dff2',
              borderRadius:20,
              position:'relative'
            }}>
              <View style={{backgroundColor:'#9957eb',width:'100%',height:'30%',borderTopLeftRadius:20,borderTopRightRadius:20}} />
              <View style={{backgroundColor:'white',position:'absolute', alignSelf:'center',alignItems:"center", marginTop:profileMarginModal,width:110,height:110,borderRadius:100,justifyContent:'center'}}>
                <Image
                  source={require('../SurveyApp/assets/icon/profile_128.png')}
                  style={{
                    height:100,
                    width:100,
                    
                  }}
                />
              </View>
              <TouchableOpacity onPress={()=>setmodalVisibleProfil(false)} style={{
                position:'absolute',
                alignSelf:'flex-end',
                padding:5
              }}>
                <Image
                  source={require('../SurveyApp/assets/icon/no.png')}
                  style={{
                    height:30,
                    width:30,
                  }}
                />
              </TouchableOpacity>
              <View style={{alignItems:'center',height:'50%'}}>
                <View style={{marginTop:60}} />
                <Text style={{color:'black',fontSize:20,fontWeight:'bold'}}>{authState?.name}</Text>
                <Text style={{color:'grey'}}>{authState?.email}</Text>
              </View>
              <View style={{height:'20%',alignItems:'center',justifyContent:'center',paddingBottom:10}}>
                <TouchableOpacity onPress={logout} style={{flexDirection:'row',alignItems:'center',columnGap:5}}>
                  <Image
                    source={require('../SurveyApp/assets/icon/exit.png')}
                    style={{
                      height:30,
                      width:30,
                    }}
                  />
                  <Text style={{color:'black'}}>Logout</Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
      </Modal2>
    </>

    )
  };
  const geonetLogo = () => {
    return(<>
      <View>
      <Image
            source={require('../SurveyApp/assets/img/Geonet_polos.png')}
            style={{height: 35,
              width: 115}}
          />
      </View>
    </>

    )
  };
  const geonetLogo2 = () => {
    return(<>
      <View>
      <Image
            source={require('../SurveyApp/assets/img/geonet_putih.png')}
            style={{height: 40,
              width: 140}}
          />
      </View>
    </>

    )
  };
  return (
    <NavigationContainer>
        <Stack.Navigator>
          { authState?.authenticated&&authState?.token ?
            <Stack.Screen name='Home' component={HomeScreen}
              options={{
                headerStyle: {
                  backgroundColor: '#34A6F8',
                },
                headerRight: geonetLogo,
                headerTintColor: '#FFFFFF',
                headerShadowVisible: false,
              }}
            />
            : 
            <Stack.Screen name='Login' component={LoginScreen}
            options={{
              title: 'Mobile Survey App',
              headerTitleStyle: {
                fontSize:20,
                fontWeight:'bold'
              },
              headerStyle: {
                backgroundColor: '#FFFFFF',
              },
              headerTintColor: '#000000',
              headerShadowVisible: false,
              headerRight: geonetLogo
            }}/>
          }
          <Stack.Screen name="Survey" component={SurveyPage}
            options={{
              headerStyle: {
                backgroundColor: '#34A6F8',
              },
              headerRight: geonetLogo2,
              headerBackVisible:false,
              headerTintColor: '#FFFFFF',
              headerShadowVisible: false,
          }}/>
          <Stack.Screen name="Survey Penerangan Jalan Umum" component={SurveyPJU}
            options={{
              headerStyle: {
                backgroundColor: '#34A6F8',
              },
              // headerRight: geonetLogo2,
              // headerBackVisible:false,
              headerTintColor: '#FFFFFF',
              headerShadowVisible: false,
              headerTitleStyle: {
                fontSize:20
              }
          }}/>
          <Stack.Screen name="Survey Pipa PDAM" component={SurveyPDAM}
            options={{
              headerStyle: {
                backgroundColor: '#34A6F8',
              },
              // headerRight: geonetLogo2,
              // headerBackVisible:false,
              headerTintColor: '#FFFFFF',
              headerShadowVisible: false,
              headerTitleStyle: {
                fontSize:20
              }
          }}/>
          <Stack.Screen name="Survey Land Permit" component={SurveyPermit}
            options={{
              headerStyle: {
                backgroundColor: '#34A6F8',
              },
              // headerRight: geonetLogo2,
              // headerBackVisible:false,
              headerTintColor: '#FFFFFF',
              headerShadowVisible: false,
              headerTitleStyle: {
                fontSize:20
              }
          }}/>
          <Stack.Screen name="PJU Map Collect" component={MapCollectScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="PJU Collecting" component={CollectScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            orientation: 'portrait',
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Sent" component={SendListScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Sent Penerangan Jalan Umum" component={SentListPJU}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Sent Pipa PDAM" component={SentListPDAM}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Sent Land Permit" component={SentListPermit}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Inbox" component={InboxListScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Inbox Penerangan Jalan Umum" component={InboxPJU}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Inbox Pipa PDAM" component={InboxPDAM}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Inbox Land Permit" component={InboxPermit}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="MapView" component={MapViewScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Edit" component={EditScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Draft" component={DraftListScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Draft Penerangan Jalan Umum" component={DraftPJU}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Draft Pipa PDAM" component={DraftPDAM}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Draft Land Permit" component={DraftPermit}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Setting" component={SettingScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="My Account" component={MyAccount}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Change Password" component={ChangePass}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Profile" component={ProfileScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="PDAM Map Collect" component={MapCollectLineScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="PDAM Collecting" component={CollectLineScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="PDAM Editing" component={EditLineScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Permit Map" component={MapCollectPolygonScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Permit Collecting" component={CollectPolygonScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Permit Editing" component={EditPolygonScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Map View Polygon" component={MapViewPolygonScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
          <Stack.Screen name="Map View Line" component={MapViewLineScreen}
          options={{
            headerStyle: {
              backgroundColor: '#34A6F8',
            },
            headerTintColor: '#FFFFFF',
            headerShadowVisible: false,
            headerTitleStyle: {
              fontSize:20
            }
          }}/>
        </Stack.Navigator>
      </NavigationContainer>
  )
}
const styles = StyleSheet.create({
  centeredView: {
    flex: 1,
    alignItems: 'flex-end',
    marginTop: 15,
    padding: 10
  },
  centeredViewProf: {
    flex: 1,
    alignItems: 'center',
    marginTop: 15,
    padding: 10
  },
  modalViewProfil: {
    width:350,
    height:400,
    backgroundColor: 'white',
    borderRadius: 20,
    paddingLeft: 20,
    paddingBottom: 20,
    paddingTop: 20,
    paddingRight: 20,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  modalView: {
    rowGap:50,
    width:200,
    height:220,
    backgroundColor: 'white',
    borderRadius: 50,
    padding: 25,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  head: {
      backgroundColor: '#34A6F8',
      flexDirection: 'row',
      justifyContent: 'space-between',
      paddingTop: 10,
      paddingBottom: 10,
      paddingLeft: 10,
      paddingRight: 10,
      textAlign: 'center'
  },
  title: {
      color: '#000000',
      fontWeight: 'bold',
      fontSize: 18,
      
  },
  profile: {
      backgroundColor: '#ADDDFF',
      borderRadius: 50,
      width:50,
      height:50,
      // position: 'absolute',
      
  },
  name: {
      fontWeight: 'bold',
      textAlign: 'center',
      paddingTop: 13,
      paddingBottom: 13,
      paddingLeft: 13,
      paddingRight: 13
  }
});
export default App;
