import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
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, Alert } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { login, RestoreProjectInProps, UploadData2 } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, copyrightText, logoImage } from '../constants/constants';
import { METHODS, getMethodName } from '../constants/methodNames';
import { MaterialCommunityIcons } from '../components/icons';
import Geolocation from 'react-native-geolocation-service';
import { requestMultiplePerms, _checkLocationPermission } from '../components/geolocation';
import DeviceInfo from 'react-native-device-info';
import SplashScreen from 'react-native-bootsplash';
import CustomLoader from '../components/CustomLoader';
import GradientButton from '../components/gradientButton';
import Graphic1 from '../assets/performics/login.svg';
import Text_eng from '../constants/Text_eng.json';
import Text_thai from '../constants/Text_thai.json';
import RNExitApp from 'react-native-exit-app';
import { widthPercentageToDP } from 'react-native-responsive-screen';

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;
  const [deviceToken, setDeviceToken] = useState({
    android_token: '',
    ios_token: '',
  });

  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();
    };
  }, []);

  function onRemoveScreen(e) {
    Alert.alert(
      "",
      "Your Device Date and Time is not correct. Please correct and restart App.",
      [
        {
          // text: "Cancel",
          // onPress: () => {},
          // style: "cancel"
        },
        {
          text: "OK", onPress: async () => {
            RNExitApp.exitApp();
          }
        }
      ]
    );
  }



  //Login failed info
  const uploadFailedLoginInfo = async (data) => {
    try {
      const urlwith_m = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
      let user_info = [];
      // Add extra columns here
      data.version = version;
      data.projectcode = props.projectCode;
      user_info.push(data);
      console.log("user_info", user_info);
      let post_data = {
        MID: "0",
        Keys: "Failed_Login_Info",
        JsonData: JSON.stringify(user_info),
        UserId: data.un
      };
      console.log("post_data", post_data);
      const res = await UploadData2(urlwith_m, post_data);
      console.log('res: 12', res);
      if (res?.UploadJsonDirectResult === "Success") {
        notify("Error login info uploaded Successfully.");
      } else {
        notify(res?.UploadJsonDirectResult);
      }
      setProcessing(false);
    } catch (err) {
      console.log(err);
      setProcessing(false);
    }
  };


  async function _getCurrentLocation() {
    console.log('_getCurrentLocation:');
    const hasPermission = await _checkLocationPermission();
    console.log('hasPermission:', hasPermission);
    if (!hasPermission) {
      notify('Please allow location permission to login');
      return;
    }
    Geolocation.getCurrentPosition(
      async (position) => {
        console.log('Got location:', position.coords);
        const loc = {
          lat: position.coords.latitude.toString(),
          lng: position.coords.longitude.toString(),
        };
        setState({ ...state, location: loc });
        await userlogin(loc);
      },
      (error) => {
        console.log('Location error:', error);
        notify('Cannot get user position');
        // fallback if GPS fails
        userlogin({ lat: '0', lng: '0' });
      },
      { enableHighAccuracy: false, distanceFilter: 0, interval: 1000, fastestInterval: 2000, timeout: 10000, maximumAge: 10000 , forceRequestLocation: true}
    );
  }



  const userlogin = async (loc) => {
    const { username, password } = state;
    let params = props.route.params ? props.route.params : {};
    let forgotMpin = params.forgotMpin || '';
    let loginInfo = await get_item('loginInfo');
    let loginDetails = {}
    if (loginInfo != null && loginInfo != "") {
      loginDetails = JSON.parse(loginInfo);
      // loginDetails.UserId
    }
    if (validate(forgotMpin, loginDetails)) {
      setProcessing(true);
      // clear_item('islogin'); clear_item('loginToken'); 
      // clear_item('loginOfDays');
      // clear_item('login_credentials');
      //  clear_item('loginInfo');
      Promise.all([
        clear_item('islogin'),
        clear_item('loginToken'),
        clear_item('loginOfDays'),
        clear_item('login_credentials'),
        clear_item('loginInfo')
      ]);
      let [manufacturer, os, imeiNo1] = await Promise.all([
        DeviceInfo.getManufacturer(),
        DeviceInfo.getSystemVersion(),
        DeviceInfo.getAndroidId()
      ]);
      const todate = new Date();
      const today = moment(todate).format("HH:mm:ss");
      // let manufacturer = await DeviceInfo.getManufacturer();
      let model = await DeviceInfo.getDeviceName();
      // let os = DeviceInfo.getSystemVersion();
      // let imeiNo1 = await DeviceInfo.getAndroidId();
      let projectInfo = await get_item('projectInfo');
      let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};
      let baseurl = projectDetails.baseURL || '';
      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 = 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');
            await uploadFailedLoginInfo(data);
          } else if (res.UserId) {
            notify('Login Success', 'SHORT');
            //set login info in global reducer
            const pdata = { islogin: true, UserId: res.UserId, SecurityToken: '', sessionData: res };
            props.set_session(pdata);
            props.set_VisitDate({ VisitDate: res.VisitDate })
            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));
            Promise.all([
              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');
            ///upload login creds if login not successed
            await uploadFailedLoginInfo(data);
          }
        }).catch((err) => {
          setProcessing(false);
          console.log('onPage Login error1', err);
        });
    }
  }

  const validate = (forgotMpin = "", loginDetails = {}) => {
    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;
    }

    if (forgotMpin == '1' && loginDetails != null && loginDetails.UserId != '' && loginDetails.UserId != null && username.toLowerCase().trim() != loginDetails.UserId.toLowerCase().trim()) {
      notify('Please enter same username', '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 (

      <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 }} />}
        <Animated.View style={[
          {
            transform: [
              { scale: illus_scale },
              { translateY: illus_ty },
            ],
          }
        ]}>
          <Graphic1 style={[customStyle.loginIllutration]} width={200} height={200} />
        </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"
              autoComplete='off'
              placeholderTextColor={PageTheme.$placeholder_color}
              value={state.username}
              onChangeText={(val) => setState({ ...state, username: val })}
            />
            <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}
              autoComplete='off'
              placeholderTextColor={PageTheme.$placeholder_color}
              value={state.password}
              onChangeText={(val) => setState({ ...state, password: val })}
              onSubmitEditing={(val) => { _getCurrentLocation(); }}
            />
            <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>

          {props?.forget_Password_on_LoginPage == true &&
            <View style={[customStyle.forgetMpinWrap, { width: widthPercentageToDP('84%') }]}>
              <TouchableOpacity style={customStyle.forgetMpinBtn} onPress={() => props.navigation.reset({ index: 0, routes: [{ name: 'ForgotPassword' }] })}>
                <Text style={customStyle.forgetMpinText}>Forgot Password?</Text>
              </TouchableOpacity>
            </View>
          }
        </Animated.View>
      </View>
    )
  }

  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)