import React, { useEffect, useContext, useState, useRef } from 'react';
import SplashScreen from 'react-native-splash-screen';
//import SplashScreen from 'react-native-bootsplash';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
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, 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 { AlertForServerDT, getProjectData, getProjectInfo, getServerDT } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, copyrightText, logoImage } from '../constants/constants';
import { requestMultiplePerms } from '../components/geolocation';
import CustomLoader from '../components/CustomLoader';
import { Ionicons } from '../components/icons';
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 [projectId, setProjectId] = useState('');
  // 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();
    };
  }, []);


  // const update_project = async () => {
  //   if (projectId != '' && projectId != null && projectId !==undefined) {
  //     setProcessing(true);
  //     await getProjectData(projectId)
  //       .then((res) => {
  //         console.log(res);
  //         setProcessing(false);
  //         console.log("reaaaa", res)
  //         if (res.success && res.responseData.projectName != null) {
  //           const pdata = getProjectInfo(res.responseData, projectId);
  //           props.set_project(pdata);
  //           //set project info in encryted local storage
  //          Promise.all([
  //             set_item('firsttime', 'done'),
  //             set_item('projectCode', projectId),
  //             set_item('projectInfo', JSON.stringify(res.responseData)),
  //           ]);
  //           // set_item('firsttime', 'done');
  //           // set_item('projectCode', projectId);
  //           // set_item('projectInfo', JSON.stringify(res.responseData));
  //           // open login screen 
  //           props.navigation.navigate('Login');
  //         } else {
  //           notify('Project not found, ensure if you have entered correct project Id', 'SHORT');
  //           Alert.alert(
  //             'Data Parsing Error',
  //             `'${res.rawData}'\n\n Please share with support team.`,
  //             [
  //               {
  //                 text: 'Ok',
  //                 onPress: () => { },
  //               },
  //             ],
  //             { cancelable: false }
  //           );
  //         }
  //       }).catch((err) => {
  //         setProcessing(false);
  //         console.log('onPage Project error', err);
  //       });
  //   }
  //   else {
  //     notify('Please enter Project Id', 'SHORT');
  //   }
  // }

  const update_project = async () => {
    if (projectId != '' && projectId != null && projectId !== undefined) {
      try {
        setProcessing(true);

        const res = await getProjectData(projectId);
        console.log(res);
        setProcessing(false);
        if (res.success && res.responseData.projectName != null) {
          const pdata = getProjectInfo(res.responseData, projectId);
          props.set_project(pdata);

          await Promise.all([
            set_item('firsttime', 'done'),
            set_item('projectCode', projectId),
            set_item('projectInfo', JSON.stringify(res.responseData)),
          ]);

          props.navigation.navigate('Login');
        } else {
          notify('Project not found, ensure if you have entered correct project Id', 'SHORT');
          Alert.alert(
            'Data Parsing Error',
            `'${res.rawData}'\n\n Please share with support team.`,
            [{ text: 'Ok', onPress: () => { } }],
            { cancelable: false }
          );
        }
      } 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 },
            ],
          }
        ]}>
          <Graphic1 style={[customStyle.loginIllutration, customStyle.mt50]} width={250} height={250} />
        </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={projectId}
              autoCorrect={false}
              autoCapitalize="none"
              importantForAutofill="no"
              returnKeyType="done"
              onChangeText={setProjectId}
              onSubmitEditing={update_project}
            />

            <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>
          </View>
        </View>
      </View>
    </Container>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(Project)