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} 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} 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';

function MiddayStock(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 allCats=[];

          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, 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){
                            // setBrandData(arr);
                            getSKU(arr,storeData1);
                        }                                
                    }
                    
                }
            },function (txn2, txnerr) { console.log(txnerr); },);
            // setProcessing(false);
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getSKU(brands=[],storeData1={}){
        
        try { 
          let {StoreId,ChainId,StateId,StoreTypeId,ExpiryStock}=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`;
                    
                    let seletlist=`PRODUCT as ProductName,PRODUCT_ID as ProductId,BRAND as BrandName,BRAND_ID as BrandId,MSL,OPENING_STOCK,MIDDAY_STOCK,CLOSING_STOCK,EXPIRY_ISOPEN,EXPIRY_STK`;
                    let sku_q=`SELECT ${seletlist} FROM ${AppTables.STOCK_DATA} 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,'MiddayStock':data.MIDDAY_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);
                                        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);
                                        // let defData={'CategoryId':item.CategoryId,'ProductId':data.ProductId,'MiddayStock':2};
                                        // allSKUData.push(defData);
                                        if(i==(txnres2.rows.length-1)){                                        
                                            item['skulist']=arr;
                                            brands[index]=item;
                                            if(index==brands.length-1){
                                                // setSKUStockData(allSKUData);
                                                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;
                })
            );          
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    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();
        }
         
    }
  
    async function submitOpeningStock(){
        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=`SELECT DISTINCT KEY_ID,CATEGORY_ID FROM ${AppTables.INSERT_OPENINGHEADER_DATA} WHERE  STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  
                if(txnres.rows.length>0){
                    for(var i=0;i<txnres.rows.length;i++){
                        let catdata=txnres.rows.item(i);
                        let c_index=i;
                        let q2=`SELECT * FROM ${AppTables.STOCK_DATA} WHERE  COMMON_ID='${catdata.KEY_ID}'`
                       
                        await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                           
                            if(txnres2.rows.length>0){
                                for(var j=0;j<txnres2.rows.length;j++){
                                    let skuData=txnres2.rows.item(j);
                                    let p_index=j;
                                    let thisCatSkuData_i=SKUStockData.findIndex(ci=>ci.CategoryId==catdata.CATEGORY_ID && ci.ProductId==skuData.PRODUCT_ID);
                                    let thisCatSkuData=thisCatSkuData_i>=0?(SKUStockData[thisCatSkuData_i] || {}):{};
                                    let md_Stock=thisCatSkuData.MiddayStock!=null && thisCatSkuData.MiddayStock!=''?thisCatSkuData.MiddayStock:'0';

                                    let new_q=`UPDATE ${AppTables.STOCK_DATA} SET MIDDAY_STOCK='${md_Stock}'  WHERE  STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and  CATEGORY_ID='${catdata.CATEGORY_ID}' and PRODUCT_ID='${skuData.PRODUCT_ID}' `;
                                   
                                    await txn.executeSql(new_q,[],async function (txn2, txnres3) { 
                                        console.log('updated midday stock',md_Stock);
                                        if(c_index==txnres.rows.length-1 &&  p_index==txnres2.rows.length-1){
                                            afterUpdate();
                                        }
                                    },function (txn2, txnerr) { console.log(txnerr);notify('Oops! Error occur while updating Midday-Stock') },);
                                }
                            }else{
                                if(c_index==txnres.rows.length-1){
                                    setProcessing(false);
                                }
                            }
                        },function (txn2, txnerr) { console.log(txnerr); },);
                    }
                }
                else{
                    setProcessing(false);
                }
              },function (txn2, txnerr) { console.log(txnerr); },);
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    async function afterUpdate(){
        setProcessing(false);
        notify('Midday-Stock updated successfully');
        props.navigation.goBack();
    }


    async function validate(){
        let isValid=true;
        var i=0,j=0;

        let isMdStockMandIndex=KPIFields.findIndex(i=>i.KPIFieldName=='MidDayStockMandatory')
        let isMdStockMandKPIObj=isMdStockMandIndex>=0?KPIFields[isMdStockMandIndex]:{};
        let isMdStockMandEnable=isMdStockMandIndex>=0?isMdStockMandKPIObj['KPIFieldEnable']:true;

        await Promise.all(
            brandData.map(async (item,index) => {
            if(isValid){
                let catId=item.CategoryId;
                
                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((isMdStockMandEnable==1 || isMdStockMandEnable=='true')  && skuData.MiddayStock!==0 && (skuData.MiddayStock==null || skuData.MiddayStock=='')){
                                    notify('Please enter Midday-Stock for '+skuItem.ProductName,'SHORT');
                                    isValid=false;
                                }else{
                                   
                                }
                            }
                        })
                    );
                }
            }
            })
        );

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

    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 md_Stock=thisCatSkuData.MiddayStock!=null?thisCatSkuData.MiddayStock:'';
                                    
                                    return(
                                        <View style={customStyle.openStk_prd_Con} key={sku_index}>
                                            <Text style={customStyle.openStk_prd_name}>{skus.ProductName}</Text>
                                            <View style={[customStyle.openStk_prddetails,customStyle.openStk_prd_borderT,customStyle.openStk_prd_borderB]}>
                                                <View style={customStyle.openStk_prdd_wrap}>
                                                    <Text style={customStyle.openStk_prdd_flabel}>Opening Stock :</Text>
                                                    <Text style={customStyle.openStk_prdd_fvalue}>{skus.OPENING_STOCK}</Text>
                                                </View>
                                            </View>
                                            <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]}>Midday 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={(md_Stock!=null?md_Stock+'':'')}
                                                            keyboardType='number-pad'
                                                            onSubmitEditing={()=>{focusToNext(cat,parseInt(catIndex),skus,parseInt(sku_index),'1')}}
                                                            onChangeText={(val)=>{ onStockValChange(cat,skus,val,'MiddayStock')}}
                                                            autoComplete='off'
                                                        />
                                                    </View>
                                                </View>
                                            </View>
                                        </View>
                                    )
                                }}/>
                            }
                        </View>
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView>
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{submitOpeningStock()}}/> 
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
  }
  
  

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