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} 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,marktext1,marktext2} 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 { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector'

function ContactConversion(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 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 [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    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 isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1);

        props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
           props.navigation.removeListener('beforeRemove', onBeforeRemove);
        };
    }, []);

    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [hasUnsavedChanges]);   
    
    function  onBeforeRemove(e){
        if (hasUnsavedChanges==true) {
            e.preventDefault(); // Prevent default behavior of leaving the screen
            onRemoveScreen(e);
        }
        else{
           return;
        }   
    }
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
              {
                text: "Cancel",
                onPress: () => {},
                style: "cancel"
              },
              { text: "OK", onPress: () => {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);} }
            ]
          );
    }
    

    async function getData(storeData1){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          
          await db.transaction(async function (txn) {        
           
            
            let q3=`Select * from ${AppTables.CONTACT_CONVERSION} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
            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}=data;
                    setTotalContact(TOTAL_CONTACT);
                    setCustomerConv(CST_CONTACT);
                }
            },function (txn2, 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);
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            await db.transaction(async function (txn) {   

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

              var values='';
              values+=` ('${StoreId}','${d2}','${TotalContact}','${CustomerConv}','${d2}') `;
              
              let add_data=`INSERT INTO ${AppTables.CONTACT_CONVERSION} (STORE_ID,VISIT_DATE,TOTAL_CONTACT,CST_CONTACT,ADDED_DATE) VALUES ${values} `;
             
              await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                console.log('cc added');
                notify('Contact conversion added successfully','SHORT');
                setProcessing(false);
                props.navigation.goBack();
              },function (txn2, 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)){
            isValid=false;
            notify('Please enter total contacts for today','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');
        }

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


    function onSaveCancel(){
        setShowAlert(false);
    }

    async function onTotalContactChange(val){
        if(!isNaN(val)){
            if(val.includes('.')){
                notify('Please enter whole numbers only','SHORT');
                return;
            }
        }

        setTotalContact(val);
        setHasUnsavedChanges(true);
    }

    async function onCustomerConvChange(val){
        if(!isNaN(val)){
            if(val.includes('.')){
                notify('Please enter whole numbers only','SHORT');
                return;
            }
        }

        setCustomerConv(val);
        setHasUnsavedChanges(true);
    }


    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={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  
                            style={customStyle.ccCard_input} 
                            value={(TotalContact+'')}
                            keyboardType={'number-pad'}
                            onEndEditing={(e)=>{console.log('on focus out'); if(CustomerConv!='' && CustomerConv!=null ) validate();}}
                            onChangeText={(val)=>{onTotalContactChange(val);}}
                            autoComplete='off'
                        />

                    </View>
                </View>
                <View style={[customStyle.contactConvCardCol]}>
                    <View style={customStyle.ccCard_FormGrp}>
                        <Text style={customStyle.ccCard_lbl}>Customer Converted</Text>
                        <TextInput  
                            style={customStyle.ccCard_input} 
                            value={(CustomerConv+'')}
                            keyboardType={'number-pad'}
                            onEndEditing={(e)=>{console.log('on focus out'); if(TotalContact!='' && TotalContact!=null ) validate();}}
                            onChangeText={(val)=>{ onCustomerConvChange(val);}}
                            autoComplete='off'
                        />
                    </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);