import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { SafeAreaView } from 'react-native-safe-area-context'
import { useRoute } from '@react-navigation/native';
import CustomButton from '../components/customButton';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { StatusBar, Image, KeyboardAvoidingView, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, PermissionsAndroid, Animated, Keyboard } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import { notify } from '../components/notify';
import moment from 'moment';
import { login, RestoreProjectInProps } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, copyrightText, baseurl, logoImage } from '../constants/constants';
import { METHODS, getMethodName } from '../constants/methodNames';
import { MaterialCommunityIcons } from '../components/icons';
// import { TouchableOpacity } from 'react-native-gesture-handler';

// import Geolocation from '@react-native-community/geolocation'

import Geolocation from 'react-native-geolocation-service';

import { requestMultiplePerms, _checkLocationPermission, checkPermissions } from '../components/geolocation';
import DeviceInfo from 'react-native-device-info';
import SplashScreen from 'react-native-splash-screen';
import CustomLoader from '../components/CustomLoader';
import { SvgUri, SvgXml } from 'react-native-svg';
import GradientButton from '../components/gradientButton';
import { Ionicons } from '../components/icons';

import Graphic1 from '../assets/performics/login.svg';

import Text_eng from '../constants/Text_eng.json';
import Text_thai from '../constants/Text_thai.json';


function Login(props) {

  const route = useRoute();

  // get all theme styles acc to current theme set 
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const globalStyle = globalStyles(props.DarkMode, route.name);

  const [state, setState] = useState({ username: '', password: '', showPass: false, location: { lat: '', lng: '' } });
  const [processing, setProcessing] = useState(false);
  const animatedEffects = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    SplashScreen.hide();
    requestMultiplePerms(); // check for permissions
    RestoreProjectInProps(props);

    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {


        Animated.timing(animatedEffects, {
          toValue: 1,
          duration: 400,
          useNativeDriver: (Platform.OS == 'ios' ? false : true),
        }).start();
      }
    );
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {

        Animated.timing(animatedEffects, {
          toValue: 0,
          duration: 400,
          useNativeDriver: (Platform.OS == 'ios' ? false : true),
        }).start();
      }
    );
    return () => {
      keyboardDidHideListener.remove();
      keyboardDidShowListener.remove();
    };
  }, []);


 


  // async function _getCurrentLocation() {
  //   const hasPermission = await _checkLocationPermission();
  //   console.log("hasPermission", hasPermission);
  //   if (hasPermission == true) {
  //     let ssss = Geolocation.getCurrentPosition();

  //     console.log('Geolocation==>', ssss);

  //     Geolocation.getCurrentPosition(
  //       async (position) => {
  //         let loc = { lat: position.coords.latitude, lng: position.coords.longitude };
  //         setState({ ...state, location: loc });
  //         await userlogin(loc);
  //       },
  //       (error) => {
  //         notify('Cannot get user position', error);
  //       },
  //       { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
  //     );
  //   }
  //   else {
  //     notify('Please allow location permission to login');
  //   }
  // }

async function _getCurrentLocation() {
  try {
    const hasPermission = await _checkLocationPermission();
    console.log("Location Permission:", hasPermission);

    if (!hasPermission) {
      notify("Please allow location permission to login");
      return;
    }

    console.log("Fetching current location...");

    Geolocation.getCurrentPosition(
      async (position) => {
        console.log('User Location:', position);

        const loc = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        setState({ ...state, location: loc });

        await userlogin(loc);
      },
      (error) => {
        console.log("Location Error:", error);
        notify("Cannot get user position");
      },
      {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 0,
        forceRequestLocation: true,
        showLocationDialog: true,
      }
    );
  } catch (err) {
    console.log("Location Exception:", err);
    notify("Unable to fetch location");
  }
}




 
  const userlogin = async (loc) => {
    const { username, password } = state;

    if (validate()) {
      setProcessing(true);
      clear_item('islogin'); clear_item('loginToken'); clear_item('loginOfDays');
      clear_item('login_credentials'); clear_item('loginInfo');

      let params = props.route.params ? props.route.params : {};
      let forgotMpin = params.forgotMpin || '';

      const todate = new Date();
      const today = moment(todate).format("HH:mm:ss");
      let manufacturer = await DeviceInfo.getManufacturer();
      let model = await DeviceInfo.getDeviceName();
      let os = await DeviceInfo.getSystemVersion();
      let imeiNo1 = await DeviceInfo.getAndroidId();

      const data = { un: username, pass: password, Intime: today, lat: loc.lat, lng: loc.lng, manufacturer: manufacturer, model: model, os: os, imeiNo1: imeiNo1, imeiNo2: imeiNo1 };
      const method_name = getMethodName(METHODS.LOGIN_METHOD);
      const url = (props.baseurl || baseurl) + method_name;
      console.log(url, data)
      await login(url, data)
        .then(async (res) => {

          setProcessing(false);

          if (res.networkErr && res.error) {
            notify('Please connect to internet-' + res.error, 'SHORT');
          }
          else if (!res.false && res.error) {
            notify(res.error, 'SHORT');
          }
          else if (res.UserId) {
            notify('Login Success', 'SHORT');
            if (forgotMpin == '1') {
              clear_item('mpin');   // clear mpin;          
            }
            //set login info in global reducer
            const pdata = { islogin: true, UserId: res.UserId, SecurityToken: '', sessionData: res };
            props.set_session(pdata);
            let country = res.CountryId != null ? res.CountryId + '' : '';

            //set login info in encryted local storage
            set_item('islogin', 'done');
            let credentials = { 'un': username, 'pass': password };
            set_item('login_credentials', JSON.stringify(credentials));
            set_item('UserCountry', country);
            set_item('loginToken', res.UserId);
            set_item('loginInfo', JSON.stringify(res));

            let lngJson = country == '2' ? Text_thai : Text_eng;
            props.setStaticText(lngJson)

            // open login screen 
            let routename = 'Mpin';
            // let mpin=await get_item('mpin');
            // if(mpin!='' && mpin!=null && mpin!=undefined){
            //   routename='NoticeBoard';
            // }
           props.navigation.reset({ index: 0, routes: [{ name: routename }], });
          }
          else {
            notify('Cannot login! Something went wrong', 'SHORT');
          }
        })
        .catch((err) => {
          setProcessing(false);
          console.log('onPage Login error1', err);
        });
    }

  }

  const validate = () => {
    const { username, password } = state;
    if (username.trim().length == 0) {
      notify('Please enter username', 'SHORT');
      return false;
    }

    if (password.trim().length == 0) {
      notify('Please enter password', 'SHORT');
      return false;
    }

    return true;
  }

  const showPassword = () => {
    const { showPass } = state;
    setState({ ...state, showPass: !showPass });
  }

  function _renderAnimPart() {
    let cl_scale = 1, cl_ty = 0, pl_scale = 1, illus_scale = 1, illus_ty = 0, formty = 0;
    if (animatedEffects != null) {
      pl_scale = animatedEffects.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 0.7],
      });
      cl_scale = animatedEffects.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 0.6],
      });
      cl_ty = animatedEffects.interpolate({
        inputRange: [0, 1],
        outputRange: [0, -40],
      });
      illus_scale = animatedEffects.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 0.5],
      });
      illus_ty = animatedEffects.interpolate({
        inputRange: [0, 1],
        outputRange: [0, -160],
      });
      formty = animatedEffects.interpolate({
        inputRange: [0, 1],
        outputRange: [0, -130],
      });
    }

    return (
      <SafeAreaView>
        <View style={customStyle.keyba_inner_view}>
          <Animated.Image style={[customStyle.performics_logo,
          {
            transform: [
              { scale: pl_scale }
            ],
          }
          ]} source={require('../assets/image/PerformicsLogo.png')} />

          {props.companylogo != null && props.companylogo != '' && <Animated.Image style={[customStyle.company_logo,
          {
            transform: [
              { scale: cl_scale },
              { translateY: cl_ty },
            ],
          }
          ]} source={{ uri: props.companylogo }} />}
          {/* <View style={{height:100}}></View> */}
          <Animated.View style={[
            {
              transform: [
                { scale: illus_scale },
                { translateY: illus_ty },
              ],
            }
          ]}>
            <SvgXml style={[customStyle.loginIllutration]} width={200} height={200} xml={Graphic1} />
          </Animated.View>

          <Animated.View style={[customStyle.formCon, customStyle.mt10,
          {
            transform: [
              { translateY: formty },
            ],
          }
          ]}>
            <Text style={[customStyle.pagedescText]}>Hey There</Text>
            <Text style={customStyle.pageText}>Login to your account</Text>

            <View style={[customStyle.formGroup, customStyle.mt20]}>
              <TextInput
                style={[customStyle.inputStyle, customStyle.pl40]}
                placeholder="Username"
                placeholderTextColor={PageTheme.$placeholder_color}
                value={state.username}
                onChangeText={(val) => setState({ ...state, username: val })}
                autoComplete='off'
              />
              <MaterialCommunityIcons style={customStyle.formInputLeftIcon} size={18} name='account-outline' color={PageTheme.$placeholder_color} />
            </View>
            <View style={[customStyle.formGroup, customStyle.mt10]}>
              <TextInput
                style={[customStyle.inputStyle, customStyle.pl40, customStyle.pr40]}
                placeholder="Password"
                secureTextEntry={!state.showPass}
                placeholderTextColor={PageTheme.$placeholder_color}
                value={state.password}
                onChangeText={(val) => setState({ ...state, password: val })}
                onSubmitEditing={(val) => { _getCurrentLocation(); }}
                autoComplete='off'
              />
              <MaterialCommunityIcons style={customStyle.formInputLeftIcon} size={16} name='lock-outline' color={PageTheme.$placeholder_color} />
              <TouchableOpacity style={customStyle.show_pass_btn} onPress={showPassword}>
                {state.showPass && <MaterialCommunityIcons color={PageTheme.$placeholder_color} name='eye'></MaterialCommunityIcons>}
                {!state.showPass && <MaterialCommunityIcons color={PageTheme.$placeholder_color} name='eye-off'></MaterialCommunityIcons>}
              </TouchableOpacity>
            </View>



          </Animated.View>


        </View>
      </SafeAreaView>
    )
  }



  return (
    <Container {...props}>
      {processing && <CustomLoader title="Logging In..." />}
      <View style={[customStyle.projectPageWrapper]}>
        <ScrollView
          style={[customStyle.projectScrollCon]}
          contentContainerStyle={customStyle.projectCon}
        >
          {_renderAnimPart()}
        </ScrollView>


        <View style={[customStyle.footerView]}>
          <GradientButton {...props} title={'Login'} onPress={() => { _getCurrentLocation(); }} />
          <View style={[customStyle.signatureBox, customStyle.mt20]}>
            <Text style={customStyle.signatureText}>{version}</Text>
            <Text style={customStyle.signatureText}>{copyrightText}</Text>
          </View>
        </View>
      </View>
    </Container>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(Login)