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, Keyboard} 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, resizeImage, restore_ImageWithMetaData, validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath,ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome,Fontisto, 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'
import { CustomPicker } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import DateTimePicker from '@react-native-community/datetimepicker';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg4 from '../assets/performics/camera_asterisk.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';

function MissedCallView(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();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    
    const [ShowDatePicker1, setShowDatePicker1] = useState(false);
    const [ShowDatePicker, setShowDatePicker] = useState(false);
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    
    const [AddVisibility, setAddVisibility] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [isAddVisPresent, setIsAddVisPresent] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [Categories, setCategories] = useState([]);
    const [SubCategories, setSubCategories] = useState([]);
    const [Brands, setBrands] = useState([]);
    const [DisplayList, setDisplayList] = useState([]);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [clickImageType,setClickImageType]= useState('1');
    const [toRemoveId,setToRemoveId]= useState('');
    const [toRemoveItem,setToRemoveItem]= useState({});
    const [showRemoveConfirm_M,setshowRemoveConfirm_M]= useState(false);
    const [showRAllC_M,setShowRAllC_M]= useState(false);
    const [KPIFields, setKPIFields] = useState([]);
    const [dateValue, setDateValue] = useState('');
    const [FromDate, setFromDate] = useState('');
    const [FromDate2, setFromDate2] = useState(new Date());

    const [ToDate, setToDate] = useState('');
    const [ToDate2, setToDate2] = useState(new Date());

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [ImgMadCount, setImgMadCount] = useState({img1:0,img2:0});

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(AddVisibility);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');

    const [showSwitchCamera,setShowSwitchCamera]= useState(false);
    const [OTPValidation,setOTPValidation]= useState(false);


    const VisFormDataRef=React.useRef(AddVisFormData);
    const isAddVisPresentRef=React.useRef(isAddVisPresent);

    // AddVisibility,AddVisFormData,isAddVisPresent,pro

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        setStoreCameraAllow(cameraAllow);
        
        let isAdhoc=params.isAdhoc || false;

        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
            
        getData(storeData1,menu1);

        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
            AppStateSubscription.remove();
            // AppState.removeEventListener('change', (pro)=>{ _handleAppStateChange(AddVisibility,AddVisFormData,isAddVisPresent,pro)});
            return unsubscribe;
        };
    }, []);

   

     const _handleAppStateChange = async (nextAppState) => {
        if(nextAppState =='background' && hasUnsavedChangesRef.current==true){
           let newData = {
               storeBGData:WindowDataRef.current,
               menuName:ScreenNameRef.current,
               StoreId1:StoreIdRef.current,
               AddFormData:VisFormDataRef.current,
               isVisPresent:isAddVisPresentRef.current,
               visiteDate:d2
           }
           let WindowsStr= JSON.stringify(newData)
           await set_item('storeData',WindowsStr); 
       }
     }
    
    useEffect(() => {
        // props.navigation.removeListener('beforeRemove', onBeforeRemove);
        // props.navigation.addListener('beforeRemove', onBeforeRemove);
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]); 


    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 
    
    function BgUnsavedChanges(val){
        hasUnsavedChangesRef.current=val
        setHasUnsavedChanges(val);
    }

    function BgWindowData(val){
        WindowDataRef.current=val
        setAddVisibility(val);
    }

    function BgAddVisFormData(val){
        VisFormDataRef.current=val
        setAddVisFormData(val);
    }

    function BgIsAddVisPresent(val){
        isAddVisPresentRef.current=val
        setIsAddVisPresent(val);
    }

    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
              {
                text: ST.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,menu1){        
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;

            let AllKPIFields=await getKPIFields(menu1);
            setKPIFields(AllKPIFields);

            let isOTPValiIndex=AllKPIFields.findIndex(i=>i.ScreenName=='ONEAPPMISSEDCALL' && i.KPIFieldName=='OTPOnlyNumber');
            let isOTPValiKPIObj=isOTPValiIndex>=0?AllKPIFields[isOTPValiIndex]:{};
            let isOTPVali=isOTPValiIndex>=0?isOTPValiKPIObj['KPIFieldEnable']:false;
            let isOTPValiFlag=isOTPVali=="true"|| isOTPVali==true
            
            // let otpCondRes=isOTPVali=="OTPOnlyNumber"
            setOTPValidation(isOTPValiFlag)

            let isFromDateIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='ShowFromDate');
            let isFromDateKPIObj=isFromDateIndex>=0?AllKPIFields[isFromDateIndex]:{};
            let isFromDateEnable=isFromDateIndex>=0?isFromDateKPIObj['KPIFieldEnable']:true;
    
            let isToDateIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='ShowToDate');
            let isToDateKPIObj=isToDateIndex>=0?AllKPIFields[isToDateIndex]:{};
            let isToDateEnable=isToDateIndex>=0?isToDateKPIObj['KPIFieldEnable']:true;

            // set switch camera flag as defined in mapping menu flag (if exists)
            let SwitchingCameraI=AllKPIFields.findIndex(i=>i.KPIFieldName=='SwitchingCamera');
            let SwitchingCameraObj=SwitchingCameraI>=0?AllKPIFields[SwitchingCameraI]:{};
            let SwitchingCamera=SwitchingCameraI>=0?SwitchingCameraObj['KPIFieldEnable']:false;
            setShowSwitchCamera(SwitchingCamera);


            //   if(isFromDateEnable==true && (FromDate=='' || FromDate==null) )
            //   {
            //     let d1=moment().format('DD/MM/YYYY');
            //     setFromDate(d1);
            //   }

            let storeBGData1=[],bgStoreJson={},isBgDataExists=false;
            let windData =await get_item('storeData')
            console.log("bg storeData:",windData);
            if(windData!=null && windData!=''){
                let StoreJson = JSON.parse(windData)
                let { storeBGData,menuName,StoreId1,AddFormData,visiteDate }= StoreJson
                if(menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                    isBgDataExists=true;
                    bgStoreJson=StoreJson
                    if(storeBGData.length>0){
                        storeBGData1=storeBGData;
                        BgWindowData(storeBGData)
                    }

                    if(AddFormData!=null && Object.keys(AddFormData).length>0){
                        let {CategoryId,SubCategoryId,FromDate,ToDate}=AddFormData;
                        // load subcategories if category exists 
                        if(CategoryId!=null && CategoryId!=''){
                            loadData(CategoryId,'SubCategories');
                        }
                        if(SubCategoryId!=null && CategoryId!=''){
                            loadData(SubCategoryId,'Brands');
                        }
                        if(FromDate!=null && FromDate!=''){
                            setFromDate(FromDate);
                            setFromDate2(new Date(FromDate));
                        }
                        if(ToDate!=null && ToDate!=''){
                            setToDate(ToDate);
                            setToDate2(new Date(ToDate));
                        }
                        BgAddVisFormData(AddFormData)
                    }
                    BgUnsavedChanges(true)
                }
            }
            await db.transaction(async function (txn) {        
                
                let q=`Select Distinct p.CategoryId,p.CategoryName from Product_Master p where (p.IsCompetitor='0' or p.IsCompetitor=0) order by p.CategorySequence`;
                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            arr.push(data);
                            if(i==txnres2.rows.length-1){setCategories(arr);}                                
                        }
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);


                let q2=`Select Distinct DisplayId,DisplayName from Master_Display where (Additional='1' or Additional=1)`;
                await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            arr.push(data);
                            if(i==txnres2.rows.length-1){setDisplayList(arr);}                                
                        }
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);

                
                let q3=`Select * from ${AppTables.MISSED_CALL} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                await txn.executeSql(q3,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            let {PRESENT,UNIQUE_CODE}=data;
                            console.log("UniqueCode----",data)
                            let datan={UniqueCode:UNIQUE_CODE}
                        
                            PRESENT==1? arr.push(datan):'';
                            let isPresent=PRESENT;
                            if(i==txnres2.rows.length-1){
                                let { menuName,StoreId1,isVisPresent,visiteDate}=bgStoreJson
                                
                                if(!isBgDataExists){
                                    BgWindowData(arr);
                                }
                                else{
                                    isPresent=isVisPresent==1?1:0;
                                }

                                
                                Animated.timing(animatedChoice, {
                                    toValue: isPresent,
                                    duration:400,
                                    useNativeDriver:false,
                                }).start();

                                BgIsAddVisPresent(isPresent);
                                // setAddVisibility(arr);
                                setProcessing(false);
                            }                                
                        }
                    }
                    else{
                        
                        if(isBgDataExists){
                            let { isVisPresent}=bgStoreJson
                            let isPresent=isVisPresent==1?1:0;
                            Animated.timing(animatedChoice, {
                                toValue: isPresent,
                                duration:400,
                                useNativeDriver:false,
                            }).start();
                            BgIsAddVisPresent(isPresent);

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

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


    async function OpenImgModal(imgPath,window,splitItem,splitItemIndex,cameraType){
        setSelectedImg(imgPath)
        setShowModal(true);
        if((imgPath!='' && imgPath!=null)){
            setShowImageSaveOp(false);
        }
        else{
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({window,splitItem,splitItemIndex,cameraType})
        // _OpenCaptureImage_Modal(imgPath,window,splitItem,splitItemIndex,cameraType)
        
      }

      function cancelImage(){
        // setImage1('');
        setSelectedImg('');
        setReCapImgModalObj({})
        setShowModal(false);
      }

    async function getImage(imgdata){
        let type=clickImageType;
        if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
            notify(ST.Cameraunavailable);
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();
              let picture_clicked_time=moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
              let picture_clicked_time_for_pic_name=moment(picture_clickedd).format('MMDDYYYY_HHmmss')

              console.log("time", picture_clicked_time);
              console.log("time1", picture_clicked_time_for_pic_name);
             let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
             let calculate_tym_date_over_img = picture_clicked_time;
            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_MissCallImg-'+calculate_tym_date_for_filename+'.jpg';
                        
            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Miss Call'+' | Date:'+calculate_tym_date_over_img;
            let addvisdata=AddVisFormData;
            let image_key='Image1';
            let image_path_key='Image1Path';
            addvisdata[image_key]=filename;
            
            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri='file://'+imagePath;
                addvisdata[image_path_key]=uri; 

                setSelectedImg(uri)
                BgAddVisFormData(addvisdata)
                BgUnsavedChanges(true)
                setrerenderdata2(!rerenderdata2);

                // add metdata then resize image and restored back to the imagePath
                let restore_data={"destFilePath":imagePath,"imgurl":imgurl,imgWidth,imgHeight,mark_text1,mark_text2}
                let is_restored=await restore_ImageWithMetaData(restore_data,imgdata);
                console.log("image restored:",is_restored);
            })
            .catch(err => {
                console.log('ERROR: image file write failed!!!');
                console.log(err.message, err.code);
            });          
        }        
    }
  
    function _OpenCaptureImage_Modal(img){
       
        const isImageCap=(img!='' || img!=null)?true:false;
        // console.log("imag pop is trigger",isImageCap,showModal,img)
        let {window,splitItem,splitItemIndex,cameraType}=reCapImgModalObj
        let camera2Label=(window && window.PromoImage2Lable) || '';
        return (
          <CustomModal 
            style={customStyle.PromoImgModal}
            title={"Missed Call Image"}
            message={camera2Label}
            titleStyle={customStyle.PromoImgModal_title}
            messageStyle={customStyle.PromoImgModal_subtitle}
            showModal={showModal}
          >
            { 
            isImageCap && 
            <View style={customStyle.PromoImgModalCon}>
              <View style={customStyle.PromoImgModal_ImgWrap}>
                <Image  style={[customStyle.PromoImgModal_Img,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:SelectedImg}} />
              </View>
              <TouchableOpacity style={customStyle.PromoImgModal_CameraSmall} onPress={()=>{openCamera('1')}}>
                <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color}/>
              </TouchableOpacity>
              
              {!showImageSaveOp &&
                <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={()=>{cancelImage()}}>
                  <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                </TouchableOpacity>
              }
            </View>
            }
          </CustomModal>
        )
      }
  
    async function openCamera(type='1'){  
        console.log('openCamera');
        setClickImageType(type);
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

    async function onSubmitData(){
        let isvalid=await validate();
        if(isvalid){
            Keyboard.dismiss();
            setShowAlert(true);
        }
    }

    async function saveData(){
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            await db.transaction(async function (txn) {   
              let q=`DELETE FROM ${AppTables.MISSED_CALL} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('av data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

              var values='';

              if(isAddVisPresent==1 && AddVisibility.length>0){
              for(var i=0;i<AddVisibility.length;i++){
                let catIndex=i;
                let item=AddVisibility[catIndex];
                // STORE_ID ,VISIT_DATE ,PRESENT ,UNIQUE_CODE ,IS_UPDATED ,ADDED_DATE ;

                let {UniqueCode}=item;
                values+=values!=''?' , ':'';
                values+=` ('${StoreId}','${d2}','${isAddVisPresent}','${UniqueCode}','1','${d2}') `;
                
              }
              
              }
              else{
                values+=` ('${StoreId}','${d2}','${isAddVisPresent}','','1','${d2}') `;
              }
              
              console.log('values MISSED_CALL:',values);
              let add_data=`INSERT INTO ${AppTables.MISSED_CALL} (STORE_ID,VISIT_DATE,PRESENT,UNIQUE_CODE,IS_UPDATED,ADDED_DATE) VALUES ${values} `;
              
              await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                console.log('av added');
                notify(`Missed Call added successfully`,'SHORT');
                setProcessing(false);
                 // clear store data in local storage to avoiding re-set data for the store  
                 clear_item('storeData')
                props.navigation.goBack();
              },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(`Cannot add Missed Call`) },);
              
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    


    async function validate(){
        
        let isValid=true;
        if(isAddVisPresent==1 && AddVisibility.length<=0){
            isValid=false;
            notify(ST.Pleaseaddfirst,'SHORT');
        }

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

    async function validateForm(){
        let isValid=true;
        let {UniqueCode}=AddVisFormData;
        let isExist=AddVisibility.some(item =>item.UniqueCode==UniqueCode )

        let isOTPLengthIndex=KPIFields.findIndex(i=>i.ScreenName=='ONEAPPMISSEDCALL' && i.KPIFieldName=='OTPLength');
        let isOTPLengthKPIObj=isOTPLengthIndex>=0?KPIFields[isOTPLengthIndex]:{};
        let isOTPLength=isOTPLengthIndex>=0?isOTPLengthKPIObj['KPIFieldDisplayName']:6;
        
        if((UniqueCode=='' || UniqueCode==null )){
            isValid=false;
            notify("Please enter Unique Code",'SHORT');
        }else if(isExist){
            isValid=false;
            notify("Number is already exist",'SHORT');
        }else if((UniqueCode.length<isOTPLength)||(UniqueCode.length>isOTPLength)){
            isValid=false;
            notify(`Please enter Unique Code in ${isOTPLength} Digit`,'SHORT');
        }

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

    function onFormDataChange(val,key,type=''){
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }
        
        let data=AddVisFormData;
        data[key]=val;
        // setAddVisFormData(data);
        // setHasUnsavedChanges(true);
        BgAddVisFormData(data)
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onselectionChange(option,keyLbl,keyVal){
        let data=AddVisFormData;
        data[keyVal]=option.value;
        data[keyLbl]=option.label;
        
        CleanSelector(option,keyLbl, data)

        // setAddVisFormData(data);
        BgAddVisFormData(data)
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
      
    }

    function CleanSelector(option,keyLbl='',data={}){

        if(keyLbl=='CategoryName'){
            loadData(option.value,'SubCategories');

            // clear subcategory and brand
            data['SubCategoryId']='';
            data['SubCategoryName']='';
            data['BrandId']='';
            data['BrandName']='';

            
            data['DisplayId']=''
            data['DisplayName']=''
            data['Remark']=''
            data['Image1Path']=''

            setToDate('');
            setToDate2(new Date());

            setFromDate('');
            setFromDate2(new Date());
            // data['FromDate']='';
        }
        else if(keyLbl=='SubCategoryName'){
            loadData(option.value,'Brands');

            // clear brand
            data['BrandId']='';
            data['BrandName']='';

            data['DisplayId']=''
            data['DisplayName']=''

            data['Image1Path']=''

            data['Remark']=''

            setToDate('');
            setToDate2(new Date());

            setFromDate('');
            setFromDate2(new Date());
        }else if(keyLbl=='BrandName'){

            // clear brand

            data['DisplayId']=''
            data['DisplayName']=''

            data['Image1Path']=''

            data['Remark']=''

            setToDate('');
            setToDate2(new Date());

            setFromDate('');
            setFromDate2(new Date());
        }else if(keyLbl=='DisplayName'){

            // clear brand

            data['Image1Path']=''

            data['Remark']=''

            setToDate('');
            setToDate2(new Date());

            setFromDate('');
            setFromDate2(new Date());
        }

    }
    async function loadData(qId,type){
        try {   
        await db.transaction(async function (txn) { 
            let q=''; 
            if(type=='SubCategories') q=`Select Distinct p.SubCategoryId,p.SubCategoryName from Product_Master p where (p.CategoryId='${qId}' or p.CategoryId=${qId}) and (p.IsCompetitor='0' or p.IsCompetitor=0) order by p.SubCategorySequence`;
            else if(type=='Brands') q=`Select Distinct p.BrandName,p.BrandId from Product_Master p Where (p.SubCategoryId='${qId}' or p.SubCategoryId= ${qId}) and (p.IsCompetitor='0' or p.IsCompetitor=0) order by p.BrandSequence`;
            
            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                // console.log('rowcount:,',type,':',txnres2.rows.length);
                if(txnres2.rows.length>0){
                    let arr=[];
                    for(var i=0;i<txnres2.rows.length;i++){
                        let data =txnres2.rows.item(i);
                        arr.push(data);
                        if(i==txnres2.rows.length-1){
                            if(type=='SubCategories')setSubCategories(arr);
                            else if(type=='Brands')setBrands(arr);
                        }                                
                    }
                }
            },function (txnE,txnerr) { console.log(txnerr); },);
           
          });          
        } catch (err) {
          console.log(err);          
        }
    }

  
   
    function onChoiceSelect(val,key){
        if(val==0 && AddVisibility.length>0){
            setShowRAllC_M(true);
            return ;
        }
        var val1=val==1?1:0;
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        // setIsAddVisPresent(val);
        // setHasUnsavedChanges(true);
        BgIsAddVisPresent(val);
        BgUnsavedChanges(true)
        if(val==0){
            // setAddVisibility([]);
            // setAddVisFormData({});
            BgWindowData([])
            BgAddVisFormData({})
        }
    }

    function onConfirmRemoveAll(){
        // Remove all data 
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: 0,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        // setIsAddVisPresent(0);
        // setHasUnsavedChanges(true);
        // setAddVisibility([]);
        // setAddVisFormData({});
        BgIsAddVisPresent(0);
        BgUnsavedChanges(true)
        BgWindowData([])
        BgAddVisFormData({})
        setShowRAllC_M(false);
    }

    function onSaveCancel(){
        setShowAlert(false);
    }

    async function Add_AddVis(){
        let isValid=await validateForm();
        console.log('isValid add:',isValid);
        if(isValid){
            let arr=AddVisibility;
            // let {CategoryName,CategoryId,SubCategoryName,SubCategoryId,BrandName,BrandId,DisplayName,DisplayId,Remark,Image1,Image1Path}=AddVisFormData;

            // let index=AddVisibility.findIndex(i=>i.CategoryId==CategoryId && i.SubCategoryId==SubCategoryId && i.BrandId==BrandId && i.DisplayId==DisplayId);
            // if(index>=0){
            //     notify(ST.Thisvisibilityhasalreadybeenadded,'LONG');
            // }
            // else{
                arr.push(AddVisFormData);
                // setAddVisibility(arr);
                // setHasUnsavedChanges(true);
                BgWindowData(arr)
                BgUnsavedChanges(true)
                notify(ST.AdditionalVisibilityaddedsuccessfully,'LONG');
                setrerenderdata(!rerenderdata);
                
                // clear data
                setFromDate('');
                BgAddVisFormData({})
                setToDate('');
                // setAddVisFormData({});
            // }
        } 
        
    }

    function showRemoveConfirm(item,index){
        setToRemoveId(index);
        setToRemoveItem(item);
        setshowRemoveConfirm_M(true);
    }

    function Remove_AddVis(){
        let index=toRemoveId
        let item=toRemoveItem;
        let arr=AddVisibility;
        console.log('toRemoveId:',index);
        if(index>=0 && index<arr.length){
            arr.splice(index,1);
            // setAddVisibility(AddVisibility);
            // setHasUnsavedChanges(true);
            BgWindowData(AddVisibility)
            BgUnsavedChanges(true)
            notify(ST.Visibilityremovedsuccessfully,'LONG')
            setrerenderdata(!rerenderdata);
        }
        else{
            notify(ST.CannotremoveVisibilitynotfound,'LONG')
        }
        setToRemoveId('');
        setToRemoveItem({});
        setshowRemoveConfirm_M(false);
        
    }
    

    function renderDatePicker(curDate,setTimeStamp,setDate,ColumnName,setShowDate){
        // PODate2,setPODate2,setPODate,setShowDatePicker
        let today=new Date();
        console.log('renderDatePicker:',curDate,FromDate);
        let d1=curDate!=null && curDate!=''?curDate:new Date();
        // let d1=new Date();
        console.log('d1 date:',d1);
        return (
            <DateTimePicker
            testID="dateTimePicker"
            value={d1}
            mode={'date'}
            display="default"  
            // maximumDate={today}
            onChange={(event, selectedDate)=>{
                console.log('onchange date',selectedDate);
                if(selectedDate!=null){
                    console.log('change date',selectedDate);
                    let d2=moment(selectedDate).format('DD/MM/YYYY');
                    let dateString=String(d2)
                    setShowDate(false);
                    setTimeStamp(selectedDate);
                    setDate(d2);
                    onFormDataChange(dateString,ColumnName)

                }
            }}
        
            />    
        );
    }
    
   
    function _render_addVisFormTop(){
        let xpos=0;
        if(animatedChoice!=null ){
            xpos=animatedChoice.interpolate({
                inputRange:[0,1],
                outputRange:[0,-75],
            });
        }


        return (
            <View style={[customStyle.addvisCon]}>
                <View style={[customStyle.addvis_pCon]}>
                        <Text style={[customStyle.addvis_pText]}>{"Add unique code?"}</Text>
                        <View style={customStyle.addvis_pChoiceBoxCon}>
                            <View style={[customStyle.openStk_prd_choiceBox,customStyle.addvis_pChoiceBoxbg]}>
                                <Animated.View style={[customStyle.openStkCh_absolutebg,customStyle.openStkCh_con_active,(isAddVisPresent=='1'?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),
                                {
                                    transform: [{
                                        translateX:xpos
                                    }],
                                }
                                ]}></Animated.View>
                                <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect(1,'isPresent')}}>
                                    <Text style={[customStyle.openStkCh_text,(isAddVisPresent==1?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={()=>{onChoiceSelect(0,'isPresent')}}>
                                    <Text style={[customStyle.openStkCh_text,(isAddVisPresent==0?customStyle.openStkCh_textactive:{})]}>{ST.No}</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                        
                </View>
                {
                isAddVisPresent==1 && (rerenderdata== rerenderdata) && 
                <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.addVisScroll}>
                <View style={customStyle.addVisForm}>
                    <View style={customStyle.addVisRow}>
                                                
                        <View style={[customStyle.addVisCol100]}>
                            <View style={[customStyle.addVisFormGrp,{flexDirection:"row",justifyContent:"space-between"}]}>
                                <Text style={customStyle.addVisLabel}>{"Unique Code"}</Text>
                                <TextInput  
                                style={[customStyle.addVisInputStyle,{width:"47%"}]} 
                                autoComplete='off'
                                value={(AddVisFormData.UniqueCode || '')}
                                onChangeText={(val)=>{onFormDataChange(val,'UniqueCode',OTPValidation?'numeric':"alphanumeric");}}
                                />
                            </View>
                        </View>
                        
                        <View style={customStyle.addVis_btnWrap}>
                            <TouchableOpacity style={customStyle.addVis_btn} onPress={()=>{Add_AddVis()}}>
                                <Text style={customStyle.addVisBtnText}>{ST.Add}</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
                <View style={customStyle.addVis_list}>
                    <Text style={customStyle.addVis_listhdrText}>{'Added Codes'}</Text>
                    <View style={customStyle.addVis_listInner}>
                        {
                            AddVisibility.length>0 &&
                            AddVisibility.map((item,index)=>{
                                console.log(item);
                                return (
                                    <View key={index} style={customStyle.addVis_listItem}>
                                        <View style={customStyle.addVis_listI_row2}>
                                            <View style={[customStyle.addVis_listIcol100]}>
                                                <View style={customStyle.MissCall_listI_row}>
                                                    <Text style={customStyle.addVis_listI_Label}>{'Unique Code :'}</Text>
                                                    <Text style={customStyle.addVis_listI_Val}>{item.UniqueCode}</Text>
                                                </View>
                                                <TouchableOpacity style={customStyle.addVis_btnRemove} onPress={()=>{showRemoveConfirm(item,index)}}>
                                                    <FontAwesome name='trash' size={20} color={'red'} />
                                                </TouchableOpacity>
                                            </View>
                                        </View>
                                      
                                    </View>
                                );
                            })
                        }
                    </View>
                </View>
                </ScrollView>
                }
            </View>
        )
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props}showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {_OpenCaptureImage_Modal()}
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {ConfirmSaveAlert(props,showRemoveConfirm_M,()=>{setshowRemoveConfirm_M(false)},Remove_AddVis,'Do you really want to remove this missed call Code')}
        {ConfirmSaveAlert(props,showRAllC_M,()=>{setShowRAllC_M(false)},onConfirmRemoveAll,'Do you really want to remove this missed call Code data')}
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <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 && 
            <View style={customStyle.addVis_Wrapper}>
                {_render_addVisFormTop()}
            </View>    
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{onSubmitData()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
        
      </Container>   
    ); 
}
  
  

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