import React,{useState,useEffect,useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, Animated, AppState} 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 {getDownloadJson,getKPIFields,marktext1,marktext2,validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome, MaterialCommunityIcons} from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import cameraImg from '../assets/performics/camera_front_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { Q_getpaidvisibility } from '../constants/ConstantQueries';
import { Picker } from '@react-native-picker/picker';
import { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector'

function ContactConversion(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    const animatedChoice=useRef(new Animated.Value(0)).current;
    
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [TotalContact, setTotalContact] = useState('');
    const [CustomerConv, setCustomerConv] = useState('');
    const [TotalSampled, setTotalSampled] = useState('');

    const [TotalMaxValEnable, setTotalMaxValEnable] = useState(false);
    const [TotalMaxVal, setTotalMaxVal] = useState(null);

    const [showAlert, setShowAlert] = useState(false);
    const [SamplingFlag, setSamplingFlag] = useState(false);
    const [showTotalSampled, setShowTotalSampled] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [SamplingData, setSamplingData] = useState({});

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const TotalContactRef=React.useRef(TotalContact);
    const CustomerConvRef=React.useRef(CustomerConv);
    const TotalSampledRef=React.useRef(TotalSampled);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');

    const inputRefs = useRef({});
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let SamplingData1=params.SamplingData || {};
        let showTotalSampled1=params.showTotalSampled!=null?params.showTotalSampled:false;
        
        let isAdhoc=params.isAdhoc || false;
        let SamplingFlag1=params.SamplingFlag || false;

        setShowTotalSampled(showTotalSampled1);
        setSamplingFlag(SamplingFlag1)
        setSamplingData(SamplingData1);
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current={BgscreenName:menu1.ScreenName,BgMenuId:menu1.MenuId }
        getData(storeData1,SamplingData1,menu1,SamplingFlag1,showTotalSampled1);

        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
        return function cleanup() {
            AppStateSubscription.remove();
            return unsubscribe;
        };
    }, []);
    const _handleAppStateChange = async (nextAppState) => {
        if(nextAppState =='background' && hasUnsavedChangesRef.current==true){
           let newData = {
               storeBGData:TotalContactRef.current,
               menuName:ScreenNameRef.current && ScreenNameRef.current.BgscreenName,
               StoreId1:StoreIdRef.current,
               BgCustomerConv1:CustomerConvRef.current,
               BgMenuID: ScreenNameRef.current && ScreenNameRef.current.BgMenuId,
               BgTotalSampled1:TotalSampledRef.current,
               ScreenName:"ContactConversion",
               visiteDate:d2
           }
           let WindowsStr= JSON.stringify(newData)
           await set_item('storeData',WindowsStr); 
       }
     }

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]);   
    
    function  onBeforeRemove(e){
        if (hasUnsavedChanges==true) {
            e.preventDefault(); // Prevent default behavior of leaving the screen
            onRemoveScreen(e);
        }
        else{
           return;
        }   
    }

    function BgUnsavedChanges(val){
        hasUnsavedChangesRef.current=val
        setHasUnsavedChanges(val);
    }

    function BgTotalContact(val){
        TotalContactRef.current=val
        setTotalContact(val);
    }

    function BgCustomerConv(val){
        CustomerConvRef.current=val
        setCustomerConv(val);
    }

    function BgTotalSampled(val){
        TotalSampledRef.current=val
        setTotalSampled(val);
    }

    function onRemoveScreen(e){     
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
              {
                text: "Cancel",
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: async () => {
                BgUnsavedChanges(false)
                await clear_item('storeData')
                // setHasUnsavedChanges(false);
                props.navigation.dispatch(e.data.action);} }
            ]
          );
    }
    

    async function getData(storeData1,SamplingData1,menu1,SamplingTypeFlag,showTotalSampled1){        
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
            let {SamplingDefinitionId}=SamplingData1;
            let {ScreenName}= menu1

            let windData = await get_item('storeData')
            let isBgDataExists=false;
            if(windData!=null && windData!=''){
                let StoreJson = JSON.parse(windData)
                let { storeBGData,menuName,StoreId1,BgCustomerConv1,BgMenuID,BgTotalSampled1,visiteDate,ScreenName }= StoreJson
                if( menuName == menu1.ScreenName && menu1.MenuId==BgMenuID && StoreId1== StoreId && visiteDate==d2 && ScreenName=="ContactConversion"){
                    isBgDataExists=true;
                    BgUnsavedChanges(true)
                    if(storeBGData!=null && storeBGData!=''){
                        BgTotalContact(storeBGData);
                    }
                    
                    if(BgCustomerConv1!=null && BgCustomerConv1!=''){
                        BgCustomerConv(BgCustomerConv1)
                    }

                    if(BgTotalSampled1!=null && BgTotalSampled1!=''){
                        BgTotalSampled(BgTotalSampled1)
                    }
                }
            }

            let AllKPIFields=await getKPIFields(menu1);

          // set switch camera flag as defined in mapping menu flag (if exists)
          let MaxContactI=AllKPIFields.findIndex(i=>i.KPIFieldName=='MaxContact' && i.ScreenName==ScreenName);
          let MaxContactObj=MaxContactI>=0?AllKPIFields[MaxContactI]:{};
          let MaxContactEnable=MaxContactI>=0?MaxContactObj['KPIFieldEnable']:false;
          let MaxContactVal=MaxContactI>=0?MaxContactObj['KPIFieldDisplayName']:null;

          setTotalMaxValEnable(MaxContactEnable);
          setTotalMaxVal(MaxContactVal);

            await db.transaction(async function (txn) {        
            
                let ScreenType = SamplingTypeFlag==true ?"SamplingContactConversion":"Contact"
                
                let q3=`Select * from ${AppTables.CONTACT_CONVERSION} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' AND SCREEN_TYPE='${ScreenType}' ${ScreenType=='SamplingContactConversion'?` AND SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' `:''} `;
                await txn.executeSql(q3,[],async function (txn2, txnres2) { 
                
                    if(txnres2.rows.length>0){
                        let arr=[];
                        let data =txnres2.rows.item(0);
                        let {TOTAL_CONTACT,CST_CONTACT,TOTAL_SAMPLED}=data;
                        
                        if(!isBgDataExists){
                            BgCustomerConv(CST_CONTACT)
                            BgTotalContact(TOTAL_CONTACT)
                            BgTotalSampled(TOTAL_SAMPLED)
                        }
                        
                        inputRefs.current['input1']='';
                        inputRefs.current['input2']='';
                        if(showTotalSampled1){
                            inputRefs.current['input3']='';
                        }

                    }else{
                        
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);

                setProcessing(false);

            });          
        } catch (err) {
          console.log(err);          
        }        
    }



    async function onSubmitData(){
        let isvalid=validate();
        if(isvalid){
           setShowAlert(true);
        }
    }

    async function saveData(){
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            let {SamplingDefinitionId}=SamplingData;
            let ScreenType = SamplingFlag==true ?"SamplingContactConversion":"Contact"
            await db.transaction(async function (txn) {   

              let q=`DELETE FROM ${AppTables.CONTACT_CONVERSION} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and SCREEN_TYPE='${ScreenType}'  ${ScreenType=='SamplingContactConversion'?` AND SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' `:''}`;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('cc data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

              var totalValue = TotalContact;
              
            if((totalValue=='' || totalValue==null ||totalValue=="[object Object]")){
                totalValue=0;
            }

              var values='';
              values+=` ('${StoreId}','${d2}','${totalValue}','${CustomerConv}','${TotalSampled || '0'}','${d2}','${SamplingDefinitionId || ''}','${ScreenType}') `;
              
              let add_data=`INSERT INTO ${AppTables.CONTACT_CONVERSION} (STORE_ID,VISIT_DATE,TOTAL_CONTACT,CST_CONTACT,TOTAL_SAMPLED,ADDED_DATE,SAMPLING_DEFINITION_ID,SCREEN_TYPE) VALUES ${values} `;
             
              await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                console.log('cc added',values);
                notify('Contact conversion added successfully','SHORT');
                setProcessing(false);
                // clear store data in local storage to avoiding re-set data for the store  
                await clear_item('storeData')
                props.navigation.goBack();
              },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add contact conversion') },);
              
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    function validate(){
        let isValid=true;
        if(TotalContact!==0 && (TotalContact=='' || TotalContact==null||TotalContact=="[object Object]")){
            isValid=false;
            notify('Please enter total contacts for today','SHORT');
        }else if(TotalMaxValEnable && parseInt(TotalContact)>parseInt(TotalMaxVal)){
            isValid=false;
            notify(`Total contacts cannot be greater than ${TotalMaxVal}`,'SHORT');
        }
        else if(CustomerConv!==0 && ( CustomerConv=='' || CustomerConv==null)){
            isValid=false;
            notify('Please enter customer converted for today','SHORT');
        }
        else if((CustomerConv!='' && CustomerConv!=null && TotalContact!='' && TotalContact!=null) && (parseInt(CustomerConv)>parseInt(TotalContact))){
            isValid=false;
            notify('Customer Converted cannot be greater than Total Contacts','SHORT');
        }
        else if(showTotalSampled && TotalSampled!==0 && ( TotalSampled=='' || TotalSampled==null)){
            isValid=false;
            notify('Please enter total sampled for today','SHORT');
        }
        else if(showTotalSampled &&  (TotalSampled!='' && TotalSampled!=null && TotalContact!='' && TotalContact!=null) && (parseInt(TotalSampled)>parseInt(TotalContact))){
            isValid=false;
            notify('Total Sampled cannot be greater than Total Contacts','SHORT');
        }

        console.log('isValid:',isValid);
        return isValid;
    }


    function onSaveCancel(){
        setShowAlert(false);
    }

    async function onTotalContactChange(val,type=''){
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }

        // setTotalContact(val);
        BgTotalContact(val)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
    }       
    //  if(!isNaN(val)){



    async function focusToNext(type='1'){

        let activeKey='';
        let arr=Object.keys(inputRefs.current);
        
        activeKey='input'+type;

        let activeIndex=arr.indexOf(activeKey);
        if(activeIndex<arr.length-1){
            let nextKey = arr[++activeIndex] 
            let nextRef= inputRefs.current[nextKey];
            console.log("nextKey", nextKey)
            nextRef.focus();    
        }
        else{
            return
        }
    }

    async function onCustomerConvChange(val,type=""){
        // if(!isNaN(val)){
        //     if(val.includes('.')){
        //         notify('Please enter whole numbers only','SHORT');
        //         return;
        //     }
        // }
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }

        // setCustomerConv(val);
        // setHasUnsavedChanges(true);
        BgCustomerConv(val);
        BgUnsavedChanges(true)
    }

    async function onTotalSampledChange(val,type=""){
        //     if(val.includes('.')){
        //         notify('Please enter whole numbers only','SHORT');
        //         return;
        //     }
        // }
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }
        BgTotalSampled(val);
        BgUnsavedChanges(true)
    }


    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={SamplingFlag? "S-Conversion":currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper,customStyle.zIndex0]}>
          <View style={[customStyle.pageContentWrapper]}>
          { Object.keys(storeData).length>0 && 
          <ScrollView contentContainerStyle={customStyle.contactConvWrap}>
            <View style={customStyle.contactConvCard}>
                <View style={customStyle.contactConvCardRow}>
                <View style={[customStyle.contactConvCardCol]}>
                    <View style={customStyle.ccCard_FormGrp}>
                        <Text style={customStyle.ccCard_lbl}>Total Contacts</Text>
                        <TextInput  
                            ref={(reff)=>{inputRefs.current['input1']=reff;}}
                            style={customStyle.ccCard_input} 
                            value={(TotalContact+'')}
                            keyboardType={'number-pad'}
                            autoComplete='off'
                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                            blurOnSubmit={false}
                            onSubmitEditing={()=>{focusToNext('1')}}
                            onEndEditing={(e)=>{console.log('on focus out'); if(CustomerConv!='' && CustomerConv!=null ) validate();}}
                            onChangeText={(val)=>{onTotalContactChange(val,'numeric');}}
                        />
                    </View>
                </View>
                {(props.route.params.showTotalSampled || showTotalSampled) && 
                <View style={[customStyle.contactConvCardCol]}>
                    <View style={customStyle.ccCard_FormGrp}>
                        <Text style={customStyle.ccCard_lbl}>Total Sampled</Text>
                        <TextInput  
                            ref={(reff)=>{inputRefs.current['input2']=reff;}}
                            style={customStyle.ccCard_input} 
                            value={(TotalSampled+'')}
                            keyboardType={'number-pad'}
                            autoComplete='off'
                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                            blurOnSubmit={false}
                            onSubmitEditing={()=>{focusToNext('2')}}
                            onEndEditing={(e)=>{if(TotalContact!='' && TotalContact!=null ) validate();}}
                            onChangeText={(val)=>{ onTotalSampledChange(val,'numeric');}}
                        />
                    </View>
                </View>
                }
                <View style={[customStyle.contactConvCardCol]}>
                    <View style={customStyle.ccCard_FormGrp}>
                        <Text style={customStyle.ccCard_lbl}>Customer Converted</Text>
                        <TextInput  
                            ref={(reff)=>{inputRefs.current['input'+((props.route.params.showTotalSampled || showTotalSampled)?'3':'2')]=reff;}}
                            style={customStyle.ccCard_input} 
                            value={(CustomerConv+'')}
                            keyboardType={'number-pad'}
                            autoComplete='off'
                            returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                            blurOnSubmit={false}
                            onSubmitEditing={()=>{focusToNext(((props.route.params.showTotalSampled || showTotalSampled)?'3':'2'))}}
                            onEndEditing={(e)=>{if(TotalContact!='' && TotalContact!=null ) validate();}}
                            onChangeText={(val)=>{ onCustomerConvChange(val,'numeric');}}
                        />
                    </View>
                </View>
                </View>
            </View>    
            </ScrollView>    
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{onSubmitData()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
        
      </Container>   
    ); 
}
  
  

export default connect(mapStateToProps, mapDispatchToProps)(ContactConversion);