import React, { useEffect, useContext, useState, useRef } from 'react';
import SplashScreen from 'react-native-splash-screen';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import CustomButton from '../components/customButton';
import GradientButton from '../components/gradientButton';
import { globalStyles, customStyles, GetPageTheme, HP, WP } from "../styles/Global";
import { StatusBar, Image, TextInput, View, Text, ScrollView, Platform, PermissionsAndroid, Animated, Keyboard } from 'react-native';
import { SvgFromUri, SvgFromXml, SvgUri, SvgXml, Image as SvgImage, SvgCss } from 'react-native-svg';
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 { getProjectData, getProjectInfo } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, copyrightText, logoImage } from '../constants/constants';
import { checkPermissions, requestMultiplePerms } from '../components/geolocation';
import CustomLoader from '../components/CustomLoader';
import { Ionicons } from '../components/icons';
import LinearGradient from 'react-native-linear-gradient';
import { baseurl } from '../constants/constants';
import { SafeAreaView } from 'react-native-safe-area-context';

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

//Project Page 
function Project(props) {

  // get dynamic styles based on dark theme or pageactive 
  const route = useRoute();
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const globalStyle = globalStyles(props.DarkMode, route.name);
  const [processing, setProcessing] = useState(false);
  const animatedEffects = useRef(new Animated.Value(0)).current;

  // get and define props and states 
  const [state, setState] = useState({ projectid: '' });
  // const labelAnim = useRef(new Animated.Value(0)).current;

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

    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 setGlobalData(){
  //set project info in global reducer
  // const pdata={pid:'',pname:'',pcode:'',alldata:{},baseurl:baseurl,companylogo:logoImage,imageUploadUrl:''};
  // let pi={baseurl:baseurl,companylogo:logoImage};

  // props.set_project(pdata);  

  // //set project info in encryted local storage
  // set_item('firsttime','done'); 
  // set_item('projectCode',''); 
  // set_item('projectInfo',JSON.stringify(pi)); 
  // }

  const update_project = async () => {
    // open login screen 
    // await setGlobalData();
    // props.navigation.navigate('Login');

    const { projectid } = state;
    if (projectid != '' && projectid != null) {
      setProcessing(true);
      await getProjectData(projectid)
        .then((res) => {
          console.log('PROJECT RESPONSE ==============>', res);
          setProcessing(false);
          if (res.success && res.projectName != null) {
            //set project info in global 
            const pdata = getProjectInfo(res, projectid);
            // const pdata={pid:projectid,pname:res.projectName,pcode:res.ProjectCode,alldata:res,baseurl:res.baseURL,companylogo:res.login_logo_Url,imageUploadUrl:res.imageUploadURL+'/',GeoFenceEnable:(res.GeoFenceEnable_checkin!=null && res.GeoFenceEnable_checkin==1),GeoFenceRadius:(res.GeoFenceRadius_checkin || 0) ,GFEnable_checkout:(res.GeoFenceEnable_checkout!=null && res.GeoFenceEnable_checkout==1),GFRadius_checkout:(res.GeoFenceRadius_checkout || 0),CheckOut_PhotoReq:res.PhotoRequired_Checkout };
            props.set_project(pdata);
            //set project info in encryted local storage
            set_item('firsttime', 'done');
            set_item('projectCode', projectid);
            set_item('projectInfo', JSON.stringify(res));


            // open login screen 
            props.navigation.navigate('Login');
          }
          else if (res.projectName == null) {
            notify('Project not found, ensure if you have entered correct project Id', 'SHORT');
          }
        })
        .catch((err) => {
          setProcessing(false);
          console.log('onPage Project error', err);
        });
    }
    else {
      notify('Please enter Project Id', 'SHORT');
    }
  }

  function _renderAnimPart() {
    let 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],
      });
      illus_scale = animatedEffects.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 0.5],
      });
      illus_ty = animatedEffects.interpolate({
        inputRange: [0, 1],
        outputRange: [0, -150],
      });
      formty = animatedEffects.interpolate({
        inputRange: [0, 1],
        outputRange: [0, -120],
      });
    }
    return (

      <ScrollView
        style={[customStyle.projectScrollCon]}
        contentContainerStyle={customStyle.projectCon}
      >
        <Animated.Image style={[customStyle.performics_logo,
        {
          transform: [
            { scale: pl_scale }
          ],
        }
        ]} source={require('../assets/image/PerformicsLogo.png')} />
        <Animated.View style={[
          {
            transform: [
              { scale: illus_scale },
              { translateY: illus_ty },
            ],
          }
        ]}>
          <SvgXml style={[customStyle.loginIllutration, customStyle.mt50]} width={250} height={250} xml={Graphic1} />
        </Animated.View>

        <Animated.View style={[customStyle.formCon, customStyle.mb10,
        {
          transform: [
            { translateY: formty },
          ],
        }
        ]}>
          <Text style={[customStyle.pagedescText]}>Hey There</Text>
          <Text style={customStyle.pageText}>Enter your Project Id</Text>
          <View style={[customStyle.formGroup, customStyle.mt20]}>
            <TextInput
              style={[customStyle.inputStyle, customStyle.pl40]}
              placeholder="Project Id"
              placeholderTextColor={PageTheme.$placeholder_color}
              value={state.projectid}
              onChangeText={(val) => setState({ projectid: val })}
              onSubmitEditing={(val) => { update_project(); }}
              autoComplete='off'
              keyboardType='numeric'
            />
            <Ionicons style={customStyle.formInputLeftIcon} size={16} name='briefcase-outline' color={PageTheme.$placeholder_color} />
          </View>


        </Animated.View>


      </ScrollView>

    )
  }

  return (
      <Container {...props} avoidSafeArea={true}>
        {processing && <CustomLoader />}
        <View style={[customStyle.projectPageWrapper]}>
          {_renderAnimPart()}

          <View style={[customStyle.footerView]}>
            <GradientButton {...props} title={'Next'} onPress={update_project} />
            <View style={[customStyle.signatureBox, customStyle.mt20]}>
              <Text style={customStyle.signatureText}>{version}</Text>
              <Text style={customStyle.signatureText}>{copyrightText}</Text>
              {/* <Image style={customStyle.signatureLogo} source={require('../assets/cpm_logo.png')} /> */}
            </View>
          </View>
        </View>
      </Container>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(Project)