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, KeyboardAvoidingView, BackHandler} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/ ';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,getKPIFields,marktext1,marktext2} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, 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 { ExitScreenAlert } from '../components/alert';



function BackroomStock(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 [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    
    const [SKUStockData, setSKUStockData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [KPIFields, setKPIFields] = useState([]);

    const inputRefs = useRef({});

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        
        let 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]);   
    
    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,menu1){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          
          let AllKPIFields=await getKPIFields(menu1);
          setKPIFields(AllKPIFields);
          await db.transaction(async function (txn) {        
            
            let join=' INNER join Product_Master p on c.CategoryId=p.CategoryId ';
            let join2=' INNER join Mapping_ProductAssortment mp on p.ProductId=mp.ProductId ';
            let q=`SELECT DISTINCT c.CategoryId,c.CategoryName,mp.MSL from Master_Category c ${join} ${join2}  where mp.StateId='${StateId}' and mp.ChainId='${ChainId}' and mp.StoreTypeId='${StoreTypeId}' order by p.CategorySequence`;
            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);
                        arr.push(data);
                        if(i==txnres.rows.length-1){
                            // setBrandData(arr);
                            getSKU(arr,storeData1);
                        }                                
                    }
                    
                }
            },function (txn2, txnerr) { console.log(txnerr); },);
            
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getSKU(brands=[],storeData1={}){
        try { 
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1; 
          await db.transaction(async function (txn) { 
            var allSKUData=[];
            await Promise.all(
                brands.map(async (item,index) => {
                    let join=`  inner join Mapping_ProductAssortment m on p.ProductId=m.ProductId `;
                    let join2=`  inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
                    let sku_q2=`select distinct p.ProductName,p.ProductId,p.BrandName,p.BrandId,m.MSL from Product_Master p  ${join} ${join2} where m.ChainId='${ChainId}' and m.StateId='${StateId}' and m.StoreTypeId='${StoreTypeId}' and p.CategoryId='${item.CategoryId}' and CompanyId='1' order by p.ProductSequence`;
                    
                    var sku_q='';
                    let seletlist=` PRODUCT as ProductName,PRODUCT_ID as ProductId,MSL,STOCK`;
                    
                    if (item.CategoryId == 0) {
                        sku_q=`SELECT ${seletlist} FROM ${AppTables.CHILD_BACK_OF_STORE} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                    } else {
                        sku_q=`SELECT ${seletlist} FROM ${AppTables.CHILD_BACK_OF_STORE} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  and CATEGORY_ID='${item.CategoryId}'`;
                    }

                    return await txn.executeSql(sku_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);
                                inputRefs.current['input1_'+item.CategoryId+'_'+data.ProductId]='';
                                arr.push(data);
                                
                                let defData={'CategoryId':item.CategoryId,'ProductId':data.ProductId,'BackroomStock':data.STOCK,};
                                allSKUData.push(defData);

                                if(i==txnres.rows.length-1){
                                    item['skulist']=arr;
                                    brands[index]=item;
                                    if(index==brands.length-1){
                                        
                                        setSKUStockData(allSKUData);
                                        setBrandData(brands);
                                        // setrerenderdata(!rerenderdata);
                                        setProcessing(false);
                                    }
                                    return item;
                                }
                            }
                        }
                        else{
                            return await txn.executeSql(sku_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);
                                        inputRefs.current['input1_'+item.CategoryId+'_'+data.ProductId]='';
                                        arr.push(data);
                                        if(i==(txnres2.rows.length-1)){                                        
                                            item['skulist']=arr;
                                            brands[index]=item;
                                            if(index==brands.length-1){
                                                // console.log('setBrands:',brands);
                                                setBrandData(brands);
                                                setProcessing(false);
                                            }
                                            return item;
                                        }               
                                    }
                                }
                                else{
                                    return item;
                                }
                            },function (txn2, txnerr) { console.log(txnerr); setProcessing(false); return item; },);
                        }
                    },function (txn2, txnerr) { console.log(txnerr);setProcessing(false); return item; },);
                  return item;
                })
            ) .then((res)=>{
                
            });          
          });          
        } catch (err) {
          console.log(err);          
        }        
    }


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

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

              let seq_q=` select seq from sqlite_sequence where name="${AppTables.HEADER_BACK_OF_STORE}" `;
              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 (txn2, 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}=storeData;

            await db.transaction(async function (txn) {
              var values='',stock_values='';
              for(var i=0;i<brandData.length;i++){
                seq++;
                let catIndex=i;
                let item=brandData[catIndex];
                values+=values!=''?' , ':'';
                values+=` ('${StoreId}','${d2}','${item.MSL}','${item.CategoryName}','${item.CategoryId}','${d2}') `;
                let skulist=item['skulist'] || [];
               
                for(var j=0;j<skulist.length;j++){
                    let skuItem=skulist[j];
                    let {BrandId, BrandName,MSL,ProductId,ProductName}=skulist[j];
                    stock_values+=stock_values!=''?' , ':'';
                    let allSKUData=SKUStockData;
                    const skud_index=allSKUData.findIndex(ci=>ci.CategoryId==item.CategoryId && ci.ProductId==skuItem.ProductId);
                    const skud=skud_index>=0?(allSKUData[skud_index] || {}) : {};

                    let BRStock=skud['BackroomStock']!=null && skud['BackroomStock']!='undefined'?skud['BackroomStock']:'';
                    stock_values+=` ('${seq}','${StoreId}','${d2}','${item.CategoryName}','${item.CategoryId}','${ProductName}','${ProductId}','${MSL}','${BRStock}','${d2}') `;
                }
              }

              let add_StockHdr=`INSERT INTO ${AppTables.HEADER_BACK_OF_STORE} (STORE_ID,VISIT_DATE,MSL,CATEGORY,CATEGORY_ID,ADDED_DATE) VALUES ${values} `;
              let add_Stock=`INSERT INTO ${AppTables.CHILD_BACK_OF_STORE} (COMMON_ID,STORE_ID,VISIT_DATE,CATEGORY,CATEGORY_ID,PRODUCT,PRODUCT_ID,MSL,STOCK,ADDED_DATE) VALUES ${stock_values} `;
              await txn.executeSql(add_StockHdr,[],async function (txn2, txnres) { 
                console.log('stock header added');
                await txn.executeSql(add_Stock,[],async function (txn2, txnres) { 
                    console.log('stock added');
                    notify('Stock updated successfully');
                    setProcessing(false);
                    props.navigation.goBack();
                },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock') },);
              },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot add stock') },);
            });          
        } catch (err) {
            console.log(err);          
        }  
    }


    async function validate(){
        let isValid=true;

        let isBRStockMandIndex=KPIFields.findIndex(i=>i.KPIFieldName=='BackRoomStockMandatory')
        let isBRStockMandKPIObj=isBRStockMandIndex>=0?KPIFields[isBRStockMandIndex]:{};
        let isBRStockMandEnable=isBRStockMandIndex>=0?isBRStockMandKPIObj['KPIFieldEnable']:true;

        if((isBRStockMandEnable==1 || isBRStockMandEnable=='true')){
        await Promise.all(
            brandData.map(async (item,index) => {
            if(isValid){
                let skulist=item.skulist || [];
                if(skulist.length>0){
                    await Promise.all(
                        skulist.map(async (skuItem,skuIndex) => {
                            if(isValid){
                                let skuData=SKUStockData.find(ci=>ci.CategoryId==item.CategoryId && ci.ProductId==skuItem.ProductId ) || {};
                                if((isBRStockMandEnable==1 || isBRStockMandEnable=='true') &&  skuData.BackroomStock!==0 && (skuData.BackroomStock==null || skuData.BackroomStock=='')){
                                    notify('Please enter backroom stock for '+skuItem.ProductName,'SHORT');
                                    isValid=false;
                                }else{
                                   
                                }
                            }
                        })
                    );
                }
            }
            })
        );
        }
        console.log('isValid:',isValid);
        return isValid;
    }

    async function focusToNext(cat,index,sku,sku_index,inputType='1'){
        console.log('focusToNext',index);
        let data=brandData;
        let ccat_index=index;
        let skulist=cat.skulist || [];
        if(sku_index==skulist.length-1){ // if last subcategory element
            //then move to next category
            console.log('move to next cat',ccat_index,data.length)
            if(ccat_index==data.length-1){
                return;
            }
            else{
                ccat_index+=1;
                console.log('move to next cat n:',ccat_index)
                let cat1=data[ccat_index];
                let skulist1=cat1.skulist || [];
                if(skulist1.length>0){
                    let sku1=skulist1[0];
                    let refIn1=inputRefs.current['input1_'+cat1.CategoryId+'_'+sku1.ProductId];
                    console.log('move to next cat refIn1:','input1_'+cat1.CategoryId+'_'+sku1.ProductId)
                    refIn1.focus();
                }
            }
        }
        else{
            // move to next subcategory
            let sku1=skulist[sku_index+1];
            let refIn1=inputRefs.current['input1_'+cat.CategoryId+'_'+sku1.ProductId];
            refIn1.focus();
        }
         
    }


    function onStockValChange(item,skuItem,val,key){
        if(!isNaN(val)){
            if(val.includes('.')){
                notify('Please enter whole numbers only','SHORT');
                return;
            }
        }
        
        let allSKUData=SKUStockData;
        let defData={'CategoryId':item.CategoryId,'ProductId':skuItem.ProductId};
        const skud_index=allSKUData.findIndex(i=>i.CategoryId==item.CategoryId && i.ProductId==skuItem.ProductId);
        const skud=skud_index>=0?(allSKUData[skud_index] || defData) : defData;
        skud[key]=val;

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

    function _render_Alert(){
        return (
          <CustomModal 
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={'Do you really want to save data?'}
            showModal={showAlert}
          >
            <View style={customStyle.storelVisitM_options}>
             <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setShowAlert(false)}}>
                <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{saveData()}}>
                <Text style={customStyle.storelVisitM_op_btnText}>Yes</Text>
              </TouchableOpacity>
            </View>
          </CustomModal>
        )
      }
  
    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}`}/>        
        {_render_Alert()}
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper]}>
          { Object.keys(storeData).length>0 &&      
            <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={(Platform.OS=='ios'?10:-100)} >  
                  
            <FlatList 
            data={brandData}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.opening_Stock_scroll} 
            style={customStyle.opening_Stock_scrollOuter}
            renderItem={({item,index})=>{
                const cat=item;
                const catIndex=index;
                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.CategoryName}</Text>
                            </LinearGradient>
                        </View>
                        <View style={customStyle.opening_Stock_prds}>
                            { 
                                <FlatList 
                                data={item.skulist}
                                extraData={rerenderdata2}
                                renderItem={({item,index})=>{
                                    const skus=item;
                                    const sku_index=index;
                                    let thisCatSkuData_i=SKUStockData.findIndex(i=>i.CategoryId==cat.CategoryId && i.ProductId==skus.ProductId);
                                    let thisCatSkuData=thisCatSkuData_i>=0?(SKUStockData[thisCatSkuData_i] || {}):{};
                                    let BackroomStock=thisCatSkuData.BackroomStock!=null?thisCatSkuData.BackroomStock:'';
                                    return(
                                        <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                            <Text style={customStyle.openStk_prd_name}>{skus.ProductName}</Text>
                                            <View style={customStyle.openStk_prd_form}>
                                                <View style={customStyle.openStk_prd_row}>
                                                    <View style={[customStyle.openStk_prd_colflex]}>
                                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>Backroom Stock</Text>
                                                        <TextInput 
                                                            ref={(reff)=>{inputRefs.current['input1_'+cat.CategoryId+'_'+skus.ProductId]=reff;}}
                                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle]}              
                                                            placeholder=""            
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            value={(BackroomStock+'' || '')}
                                                            keyboardType='number-pad'
                                                            onSubmitEditing={()=>{focusToNext(cat,parseInt(catIndex),skus,parseInt(sku_index),'1')}}
                                                            onChangeText={(val)=>{ onStockValChange(cat,skus,val,'BackroomStock')}}
                                                            autoComplete='off'
                                                        />
                                                    </View>
                                                    
                                                </View>
                                            </View>
                                        </View>
                                    )
                                }}/>
                            }
                        </View>
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView>
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{submitBackroomStock()}}/> 
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

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