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 {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath,ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, FontAwesome, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import CameraImg from '../assets/performics/camera_front_image.svg'
import { Q_getpaidvisibility, Q_getpromotionmappingList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import CustomCamera from '../components/Camera';
import { CustomPicker2 } from '../components/CustomPicker';

function SimplePromotion(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 [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [promotionData, setPromotionData] = useState([]);
    const [globalPromoData, setGlobalPromoData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    
    const [SKUStockData, setSKUStockData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [reasons_list, setReasons_list] = useState([]);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [searchedItem, setSearchedItem]= useState('');
    const [KPIFields, setKPIFields] = useState([]);

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    const zoomView=useRef(null);
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        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,menu1);

        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]);   
    
    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [showCamera]); 
    
    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: () => {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);} }
            ]
          );
    }

    async function getData(storeData1,menu1){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          let allCats=[];
          await getKPIFields(menu1);
          await db.transaction(async function (txn) {        
            let q2=Q_getpromotionmappingList(storeData1);
            // let q2=Q_getpaidvisibility(storeData1);
            let q=`Select * From Master_NonVisibility`;
            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){
                            setReasons_list(arr);
                        }                                
                    }
                }
            },function (txnE,txnerr) { console.log(txnerr); },);

            await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                console.log('prmotion cats',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){
                            getPromotion(arr,storeData1,menu1);
                        }                                
                    }
                }
            },function (txnE,txnerr) { console.log(txnerr); },);
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getKPIFields(menu1){
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {
                let q=`select * from Mapping_MenuConfiguration where ScreenName='${menu1.ScreenName}'`;
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    if(txnres.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres.rows.length;i++){
                            let data =txnres.rows.item(i);
                            
                            let isenable=data.KPIFieldEnable=='true' || data.KPIFieldEnable==1?true:false;
                            data['KPIFieldEnable']=isenable;
                            arr.push(data);
                            if(i==txnres.rows.length-1){
                                setKPIFields(arr);
                                resolve(true)
                            }
                        }
                    }
                    else{
                        resolve(true)
                    }
                },function (txnE,txnerr) { console.log(txnerr);resolve(false) },);
            });
        }).then((val)=>{
            return val;
        }).catch((err)=>{
            console.log(err);
            return false;
        });
    }

    async function getPromotion(prom_mappings=[],storeData1={},menu1){
        
        try { 
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;     
        
          await db.transaction(async function (txn) { 
            let allSKUData=[];
            let completed_tasks=0;
            await Promise.all(
                prom_mappings.map(async (item,index) => {
                    let seletlist=`p.PROMOTION_ID as PromoId,p.PROMOTION as Promotion,p.IS_PRESENT as IsPresent,p.REASON_ID as ReasonId,p.REASON as Reason,p.IMAGE1 as Image1,m.Promotion_Line2,m.PromotionType,m.Camera1Enable,m.Camera2Enable`;
                    let sku_q=`SELECT ${seletlist} FROM ${AppTables.SIMPLE_PROMOTION_DATA} p Inner Join Mapping_Promotion m on m.PromoId=p.PROMOTION_ID  WHERE p.STORE_ID='${StoreId}' and p.VISIT_DATE='${d2}' and  p.SUB_CATEGORY_ID='${item.SubCategoryId}' `;
                    
                    let sku_q2=`SELECT DISTINCT m.PromoId as PromoId,m.Promotion as Promotion,m.Promotion_Line2,m.PromotionType,m.Camera1Enable,m.Camera2Enable FROM Mapping_Promotion m where m.SubCategoryId='${item.SubCategoryId}' and m.ChainId='${ChainId}' and m.StoreTypeId='${StoreTypeId}'and m.StateId='${StateId}'`;
                    
                    return await txn.executeSql(sku_q,[],async function (txn2, txnres) { 
                        console.log('inserted data:',txnres.rows.length);
                        if(txnres.rows.length>0){
                            let arr=[];
                           
                            for(var i=0;i<txnres.rows.length;i++){
                                let data =txnres.rows.item(i);
                                let cj_index=i;
                                let ancval=data.IsPresent==1?1:0;
                                let animatedChoice=new Animated.Value(ancval);
                                data.animatedChoice=animatedChoice;
                              
                                arr.push(data);
                                let imgpath=data.Image1!=null && data.Image1!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+data.Image1:'';
                                let defData={'SubCategoryId':item.SubCategoryId,'PromoId':data.PromoId,'isPresent':(data.IsPresent),'Image1':(data.Image1 || ''),'Image1Path':imgpath,'ReasonId':0,'Reason':(data.Reason || '')};
                                
                                allSKUData.push(defData);

                                if(cj_index==txnres.rows.length-1){
                                    item['promotionlist']=arr;
                                    prom_mappings[index]=item;
                                    if(completed_tasks==prom_mappings.length-1){
                                        setSKUStockData(allSKUData);
                                        setPromotionData(prom_mappings);
                                        setGlobalPromoData(prom_mappings);
                                        setProcessing(false);
                                    }
                                    completed_tasks++;
                                    return item;
                                }
                            }
                            
                        }
                        else{
                            return await txn.executeSql(sku_q2,[],async function (txn2, txnres2) { 
                                if(txnres2.rows.length>0){
                                    let arr=[];
                                    console.log('avlbl prmotions:',txnres2.rows.length);
                                    for(var i=0;i<txnres2.rows.length;i++){
                                        let data =txnres2.rows.item(i);
                                        let cj_index=i;
                                        let animatedChoice=new Animated.Value(0);
                                        data.animatedChoice=animatedChoice;
                                        let animatedChoiceStock=new Animated.Value(0);
                                        data.animatedChoiceStock=animatedChoiceStock;
                                        let animatedChoicePromo=new Animated.Value(0);
                                        data.animatedChoicePromo=animatedChoicePromo;
                                        arr.push(data);
                                        
                                        let defData={'SubCategoryId':item.SubCategoryId,'PromoId':data.PromoId,'isPresent':0,'Image1':'','Image1Path':'','ReasonId':0,'Reason':''};
                                        allSKUData.push(defData);
                                        
                                        if(cj_index==(txnres2.rows.length-1)){  
                                            item['promotionlist']=arr;
                                            prom_mappings[index]=item;
                                            if(completed_tasks==prom_mappings.length-1){
                                                setSKUStockData(allSKUData);
                                                setPromotionData(prom_mappings);
                                                setGlobalPromoData(prom_mappings);
                                                setProcessing(false);
                                            }
                                            completed_tasks++;
                                            return item;
                                        }               
                                    }
                                }
                                else{
                                    return item;
                                }
                                
                            },function (txnE,txnerr) { console.log(txnerr); setProcessing(false); return item; },);
                        }
                    },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); return item; },);
                  return item;
                })
            ) .then((res)=>{
                
            });          
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

  

    async function getImage(imgdata){
        let cat=getImageProps.cat || '';
        let skuItem=getImageProps.skuItem || '';
        let type=getImageProps.type || '';
        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.height;
            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('DD-MM-YYYY HH:mm:ss')
            const mark_text1=picture_clicked_time;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Promotion'+' | Date:'+picture_clicked_time;
           
            await marktext1(mark_text1,imgurl)
            .then((res)=>{
                if(res.success){
                    let uri=res.uri;
                    marktext2(mark_text2,uri,imgWidth,imgHeight)
                    .then((res)=>{
                        if(res.success){
                            
                            let picture_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                            let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_PromotionImg-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                            
                            let allData=SKUStockData;
                            let defData={'SubCategoryId':cat.SubCategoryId,'PromoId':skuItem.PromoId};
                            const cindex=allData.findIndex(ci=>ci.SubCategoryId==cat.SubCategoryId && ci.PromoId==skuItem.PromoId);
                            const imgData=cindex>=0?(allData[cindex] || defData):defData;
                            let image_key=type=='2'?'Image2':'Image1';
                            let image_path_key=type=='2'?'Image2Path':'Image1Path';
                            imgData[image_key]=filename;
                            
                            // renamefile
                            let imagePath=ImageFolderPath+currentMenu.ScreenName+"/"+filename;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri='file://'+imagePath;
                                console.log('image marker',uri);
                                imgData[image_path_key]=uri; 
                                console.log(imgData);
                                cindex>=0?allData[cindex]=imgData:allData.push(imgData);
                                
                                setSKUStockData(allData);
                                setHasUnsavedChanges(true);
                                setrerenderdata2(!rerenderdata2);
                            })
                            .catch(err => {
                                console.log('ERROR: image file write failed!!!');
                                console.log(err.message, err.code);
                            });                           
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify(ST.Pleasecaptureaimage);
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify(ST.Pleasecaptureaimage);
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }
  
    async function openCamera(cat,skuItem,type='1'){  
        setGetImageProps({'cat':cat,'skuItem':skuItem,'type':type}); 
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

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

    async function saveData(){
        setHasUnsavedChanges(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.SIMPLE_PROMOHDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              let q2=`DELETE FROM ${AppTables.SIMPLE_PROMOTION_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('promotions hdr data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

              await txn.executeSql(q2,[],async function (txn2, txnres) { 
                console.log('promotions data deleted');
              },function (txnE,txnerr) { console.log(txnerr); },);

              
              let seq_q=` select seq from sqlite_sequence where name="${AppTables.SIMPLE_PROMOHDR_DATA}" `;
              await txn.executeSql(seq_q,[],async function (txn2, txnres) { 
                if(txnres.rows.length>0){
                    let data=txnres.rows.item(0);
                    let seq=data.seq;
                    insertData(seq);
                }
                else{
                    insertData(0);
                }
              },function (txnE,txnerr) { console.log(txnerr); insertData(0); },);
             
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function insertData(seq=0){
        try {   
            console.log(seq);
            let {StoreId,ChainId,StateId,StoreTypeId,ExpiryStock}=storeData;

            await db.transaction(async function (txn) {
              var values='',child_values='',checklist_values='';
              
              for(var i=0;i<promotionData.length;i++){
                seq++;
                let catIndex=i;
                let item=promotionData[catIndex];
                values+=values!=''?' , ':'';
                values+=` ('${StoreId}','${d2}','${item.SubCategoryName}','${item.SubCategoryId}','${d2}') `;
               
                let promotionlist=item['promotionlist'] || [];
               
                for(var j=0;j<promotionlist.length;j++){
                    let skuItem=promotionlist[j];
                    child_values+=child_values!=''?' , ':'';
                    let allSKUData=SKUStockData;
                    const skud_index=allSKUData.findIndex(ci=>ci.SubCategoryId==item.SubCategoryId && ci.PromoId==skuItem.PromoId);
                    const skud=skud_index>=0?(allSKUData[skud_index] || {}) : {};
                    
                    child_values+=` ('${seq}','${StoreId}','${d2}','${item.SubCategoryName}','${item.SubCategoryId}','${skuItem.Promotion}','${skuItem.PromoId}','${skud.isPresent}','${(skud.ReasonId || 0)}','${(skud.Reason || '')}','${(skud.Image1)}','${d2}') `;
                }
              }

              let add_HdrData=`INSERT INTO ${AppTables.SIMPLE_PROMOHDR_DATA} (STORE_ID,VISIT_DATE,SUB_CATEGORY,SUB_CATEGORY_ID,ADDED_DATE) VALUES ${values} `;
             
              let add_ChildData=`INSERT INTO ${AppTables.SIMPLE_PROMOTION_DATA} (COMMON_ID,STORE_ID,VISIT_DATE,SUB_CATEGORY,SUB_CATEGORY_ID,PROMOTION,PROMOTION_ID,IS_PRESENT,REASON_ID,REASON,IMAGE1,ADDED_DATE ) VALUES ${child_values} `;
              
              
              await txn.executeSql(add_HdrData,[],async function (txn2, txnres) { 
                console.log('promotion header added');
                await txn.executeSql(add_ChildData,[],async function (txn2, txnres) { 
                    console.log('promotion child added');
                    notify(ST.Promotionupdatedsuccessfully);
                    setProcessing(false);
                    props.navigation.goBack();
                    
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.CannotupdatePromotion) },);
              },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.CannotupdatePromotion) },);
            });          
        } catch (err) {
            console.log(err);          
        }  
    }


    async function validate(){
        let isValid=true;
        await Promise.all(
            promotionData.map(async (item,index) => {
            if(isValid){
                
                let promotionlist=item.promotionlist || [];
                if(promotionlist.length>0){
                    await Promise.all(
                        promotionlist.map(async (skuItem,skuIndex) => {
                            let Camera1Enable=(skuItem.Camera1Enable==1 || skuItem.Camera1Enable=='true')?true:false;
                            if(isValid){
                                let skuData=SKUStockData.find(ci=>ci.SubCategoryId==item.SubCategoryId && ci.PromoId==skuItem.PromoId) || {};
                                if(skuData.isPresent!=0 && (skuData.isPresent==null || skuData.isPresent=='')){
                                    notify(ST.Pleaseselectifpromotionpresentornotfor+' '+item.SubCategoryName+' '+skuItem.Promotion,'SHORT');
                                    isValid=false;
                                }else if((skuData.isPresent==1) && Camera1Enable==true && ((skuData.Image1==null || skuData.Image1==''))){
                                    notify(ST.Pleaseclickallimagesfor+' '+item.SubCategoryName+' '+skuItem.Promotion,'SHORT');
                                    isValid=false;
                                }
                                else if((skuData.isPresent!=1) && ((skuData.ReasonId==null || skuData.ReasonId==''))){
                                    notify(ST.Pleaseselectreasonfor+' '+item.SubCategoryName+' '+skuItem.Promotion,'SHORT');
                                    isValid=false;
                                }
                            }
                        })
                    );
                }
            }
            })
        );

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

    function onStockValChange(item,skuItem,val,key,isChoiceSelect=0){
        let allSKUData=SKUStockData;
        let defData={'SubCategoryId':item.SubCategoryId,'PromoId':skuItem.PromoId};
        const skud_index=allSKUData.findIndex(i=>i.SubCategoryId==item.SubCategoryId && i.PromoId==skuItem.PromoId);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        skud[key]=val;
        
        if(isChoiceSelect==1 && (skud.isPresent!=1 && skud.isPromoTalkerAvlbl!=1 && skud.isStockAvlbl!=1 )){
            skud.Image1='';
            skud.Image1Path='';
        }
        skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
        
        setSKUStockData(allSKUData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    
    function onChoiceSelect(item,skuItem,val,key,animatedChoice){
        var val1=0;
        if(val==1){
            val1=1;
        }
        
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        onStockValChange(item,skuItem,val,key,1)
    }

    function onselectionChange(option,keyLbl,keyVal,otherData){
        let skuItem=otherData.skus,item=otherData.cat;
        let allSKUData=SKUStockData;
        let defData={'SubCategoryId':item.SubCategoryId,'DisplayId':skuItem.DisplayId};
        const skud_index=allSKUData.findIndex(i=>i.SubCategoryId==item.SubCategoryId && i.DisplayId==skuItem.DisplayId);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        skud[keyVal]=option.value;
        skud[keyLbl]=option.label;

        skud_index>=0?allSKUData[skud_index]=skud:allSKUData.push(skud);
        console.log('allSKUData:',allSKUData);
        setSKUStockData(allSKUData);
        setHasUnsavedChanges(true);
        setrerenderdata(!rerenderdata);
    }

    function onSaveCancel(){
        setShowAlert(false);
    }

    function FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        console.log('searchedQry',searchedQry);
        let arr=[];
        var arr2=[];
        if(searchedQry!=null && searchedQry!=''){
            
            for(let i=0;i<globalPromoData.length;i++){
                let item=globalPromoData[i];
                let promotionlist=item.promotionlist || [];
                arr2={ 'SubCategoryName':item.SubCategoryName,'SubCategoryId':item.SubCategoryId};
                let newpromotionlist=[];
                
               
                for(let j=0;j<promotionlist.length;j++){
                    let sku=promotionlist[j];
                    let {Promotion}=sku;
                    
                    if(Promotion.toLowerCase().includes(searchedQry)){
                        newpromotionlist.push(sku);
                    }
                    if(j==promotionlist.length-1){
                        arr2.promotionlist=newpromotionlist;
                        if(arr2.promotionlist.length>0){
                            arr.push(arr2);
                        }
                    }
                }

                
            }
        }
        else{
          arr=globalPromoData;
        }

        setPromotionData(arr);
        setrerenderdata(!rerenderdata)
        setrerenderdata2(!rerenderdata2)
    }
  
    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}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <CustomCamera cameraType={'back'} 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]}>
          <View style={customStyle.storel_searchbar}>
              <TextInput 
                style={[customStyle.storel_searchInput]}
                placeholder={ST.SearchbyPromotion}
                placeholderTextColor={PageTheme.$placeholder_color} 
                value={searchedItem}
                autoComplete='off'
                onChangeText={(val)=>{setSearchedItem(val); FilterStores(val)}}
              />
              <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem)}}>
                <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
              </TouchableOpacity>
          </View>
          { Object.keys(storeData).length>0 &&            
            <FlatList 
            data={promotionData}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.opening_Stock_scroll} 
            style={customStyle.opening_Stock_scrollOuter}
            renderItem={({item,index})=>{
                const cat=item;
                
                return(
                    <View style={customStyle.opening_Stock_wrap}>
                        <View style={customStyle.opening_Stock_cat}>                            
                            <LinearGradient colors={[PageTheme.$primary_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.opening_Stock_catInner}>
                                <Text style={customStyle.opening_Stock_catText}>{item.SubCategoryName}</Text>
                        
                            </LinearGradient>
                            
                        </View>
                        <View style={customStyle.opening_Stock_prds}>
                            {
                                
                                <FlatList 
                                data={item.promotionlist}
                                extraData={rerenderdata2}
                                renderItem={({item,index})=>{
                                    const skus=item;
                                    const sku_index=index;
                                    let thisCatSkuData_i=SKUStockData.findIndex(i=>i.SubCategoryId==cat.SubCategoryId && i.PromoId==skus.PromoId);
                                    let thisCatSkuData=thisCatSkuData_i>=0?(SKUStockData[thisCatSkuData_i] || {}):{};
                                    let isPresent=thisCatSkuData.isPresent!=null?thisCatSkuData.isPresent:'0';
                                    let Image1Path=(thisCatSkuData.Image1Path!=null && thisCatSkuData.Image1Path!='')?thisCatSkuData.Image1Path:'';
                                    let ReasonId=thisCatSkuData.ReasonId!=null?thisCatSkuData.ReasonId:'';
                                    let Reason=thisCatSkuData.Reason!=null?thisCatSkuData.Reason:'';
                                    
                                    let Camera1Enable=(item.Camera1Enable==1 || item.Camera1Enable=='true')?true:false;

                                    var xpos=isPresent==1?-75:0;
                                    if(skus.animatedChoice!=null ){
                                        xpos=skus.animatedChoice.interpolate({
                                            inputRange:[0,1],
                                            outputRange:[0,-75],
                                        });
                                    } 


                                    // let isCamera1EnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Camera1Enable')
                                    // let isCamera1EnableKPIObj=isCamera1EnableIndex>=0?KPIFields[isCamera1EnableIndex]:{};
                                    // let isCamera1Enable=isCamera1EnableIndex>=0?isCamera1EnableKPIObj['KPIFieldEnable']:true;
                                                        
                                    // let isCamera2EnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='Camera2Enable')
                                    // let isCamera2EnableKPIObj=isCamera2EnableIndex>=0?KPIFields[isCamera2EnableIndex]:{};
                                    // let isCamera2Enable=isCamera2EnableIndex>=0?isCamera2EnableKPIObj['KPIFieldEnable']:true;
                                  

                                    return(
                                        <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                            <Text style={[customStyle.openStk_prd_name]}>{skus.Promotion}</Text>
                                           
                                            {(skus.Promotion_Line2!=null && skus.Promotion_Line2!='undefined' && skus.Promotion_Line2!='') && <Text style={[customStyle.openStk_prd_name2]}>{(skus.Promotion_Line2 || '')}</Text>}
                                            <View style={customStyle.openStk_prd_form}>
                                                
                                                <View style={[customStyle.openStk_prd_cols,customStyle.openStk_prd_borderT,customStyle.mt10,customStyle.pt10]}>
                                                <View style={[customStyle.openStk_prd_colflex,customStyle.mb10]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.IsPresent}</Text>
                                                
                                                        <View style={customStyle.openStk_prd_choiceBoxCon}>
                                                            <View style={customStyle.openStk_prd_choiceBox}>
                                                                <Animated.View style={[customStyle.openStkCh_absolutebg,customStyle.openStkCh_con_active,(isPresent=='1'?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),
                                                                {
                                                                    transform: [{
                                                                        translateX:xpos
                                                                    }],
                                                                }
                                                                ]}></Animated.View>
                                                                <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect(cat,skus,1,'isPresent',skus.animatedChoice)}}>
                                                                    <Text style={[customStyle.openStkCh_text,(isPresent=='1'?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                                                                </TouchableOpacity>
                                                                <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={()=>{onChoiceSelect(cat,skus,0,'isPresent',skus.animatedChoice)}}>
                                                                    <Text style={[customStyle.openStkCh_text,(isPresent=='0'?customStyle.openStkCh_textactive:{})]}>{ST.No}</Text>
                                                                </TouchableOpacity>
                                                            </View>
                                                        </View>
                                                    </View>
                                                    {isPresent!='1' && <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.SelectReason}</Text>
                                                        {<CustomPicker2 {...props} Pickerdata={reasons_list} label_key={'Reason'} value_key={'ReasonId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'} onChange={onselectionChange} selected_data={{value:Reason,otherData:{cat:cat,skus:skus}}} InputStyle={customStyle.PV_selectInputStyle} selectStyle={customStyle.PV_selectStyle} />}
                                                    </View>}

                                                    {(isPresent=='1' && Camera1Enable==true) && 
                                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10]}>
                                                        <Text style={[customStyle.openStk_prd_label]}>{ST.CaptureImage}</Text>
                                                        <View style={customStyle.openStk_prdCameras}>
                                                            <View style={customStyle.openStkCameraCon}>
                                                            { (Image1Path=='' || Image1Path==null) && 
                                                                <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera(cat,skus,'1')}}>
                                                                    <CameraImg width={80} height={80}/>                                     
                                                                </TouchableOpacity>
                                                            }
                                                            { (Image1Path!='' && Image1Path!=null) && 
                                                                <View style={customStyle.osCatImageView}>
                                                                    <Image style={customStyle.osCatImage} source={{uri:Image1Path}}/>
                                                                    <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(cat,skus,'1')}}>
                                                                        <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                                    </TouchableOpacity>
                                                                </View>                                    
                                                            }       
                                                            </View>         
                                                        </View>
                                                    </View>
                                                    }
                                                    
                                                </View>
                                            
                                            </View>
                                            
                                        </View>
                                    )
                                }}/>
                            }
                        </View>
                    </View>
                );
            }}
            />
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{submitOpeningStock()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

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