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,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 { Q_GetAvailabityDefaultData } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';

function Sale(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 [SKUStockData, setSKUStockData] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    
    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);
        props.navigation.addListener('beforeRemove', onBeforeRemove);

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

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

    async function getData(storeData1){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
          
          await db.transaction(async function (txn) {   
            let q2=Q_GetAvailabityDefaultData(storeData1);

            await txn.executeSql(q2,[],async function (txn2, txnres) { 
                if(txnres.rows.length>0){
                    console.log('inputs found');
                    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){
                            getSKU(arr,storeData1);
                        }
                    }
                }
                
            },function (txn2, txnerr) { console.log(txnerr); },);
            // setProcessing(false);
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getSKU(brands=[],storeData1={}){
        console.log('getSKU')
        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 seletlist=`s.PRODUCT as ProductName,s.PRODUCT_ID as ProductId,s.MSL,s.STOCK,o.MIDDAY_STOCK,o.OPENING_STOCK`;
                    let join1=` inner join ${AppTables.STOCK_DATA} o on s.PRODUCT_ID=o.PRODUCT_ID and o.STORE_ID='${StoreId}' and o.VISIT_DATE='${d2}' `;
                    let sku_q=`SELECT ${seletlist} FROM ${AppTables.SALES} s ${join1} WHERE s.STORE_ID='${StoreId}' and s.VISIT_DATE='${d2}' and s.CATEGORY_ID='${item.CategoryId}' `;
     
                  
                    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 join3=` left join ${AppTables.STOCK_DATA} o on p.ProductId=o.PRODUCT_ID and o.STORE_ID='${StoreId}' and o.VISIT_DATE='${d2}' `;
                    let sku_q2=`select distinct p.ProductName,p.ProductId,m.MSL,o.MIDDAY_STOCK ,o.OPENING_STOCK from Product_Master p  ${join} ${join2} ${join3} where m.ChainId='${ChainId}' and m.StateId='${StateId}' and m.StoreTypeId='${StoreTypeId}' and p.CategoryId='${item.CategoryId}' and CompanyId='1' order by p.ProductSequence`;
                    
                    
                    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,'Stock':data.STOCK};
                                allSKUData.push(defData);

                                if(i==txnres.rows.length-1){
                                    item['skulist']=arr;
                                    brands[index]=item;
                                    if(index==brands.length-1){
                                        console.log('allSKUData:',allSKUData);
                                        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,'Stock':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;
                })
            ) .then((res)=>{
                
            });          
          });          
        } 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 submitData(){
        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.SALES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('sales data deleted');
              },function (txn2, txnerr) { console.log(txnerr); },);

              var stock_values='';
              for(var i=0;i<brandData.length;i++){
                let catIndex=i;
                let item=brandData[catIndex];
                
                
                let skulist=item['skulist'] || [];
                for(var j=0;j<skulist.length;j++){
                    let skuItem=skulist[j];
                    let {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] || {}) : {};
                    stock_values+=` ('${StoreId}','${d2}','${item.CategoryName}','${item.CategoryId}','${ProductName}','${ProductId}','${MSL}','${skud['Stock']}','${d2}') `;
                }
              }

              let add_Stock=`INSERT INTO ${AppTables.SALES} (STORE_ID,VISIT_DATE,CATEGORY,CATEGORY_ID,PRODUCT,PRODUCT_ID,MSL,STOCK,ADDED_DATE) VALUES ${stock_values} `;
              await txn.executeSql(add_Stock,[],async function (txn2, txnres) { 
                console.log('sales added');
                notify('Sales updated successfully');
                setProcessing(false);
                props.navigation.goBack();
              },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot update Sales') },);
             
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

   

    async function validate(){
        let isValid=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 ) || {};
                                let OS=skuItem.OPENING_STOCK || 0;
                                let MDS=skuItem.MIDDAY_STOCK || 0;
                                let maxClosingStock=parseInt(OS) + parseInt(MDS);
                                if(skuData.Stock!==0 && (skuData.Stock==null || skuData.Stock=='')){
                                    notify('Please enter stock for '+skuItem.ProductName,'SHORT');
                                    isValid=false;
                                }else if(parseInt(skuData.Stock)>maxClosingStock){
                                    notify('Sale Should not be greater than the sum of Opening-Stock and 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 onSaveCancel(){
        setShowAlert(false);
    }
    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <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}
                                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 stock=thisCatSkuData.Stock!=null?thisCatSkuData.Stock:'';
                                    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 + Midday Stock : (${skus.OPENING_STOCK} + ${skus.MIDDAY_STOCK}) :`}</Text>
                                                    <Text style={customStyle.openStk_prdd_fvalue}>{(parseInt(skus.MIDDAY_STOCK)+parseInt(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_flexlabel}>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={(stock+'' || '')}
                                                            keyboardType='number-pad'
                                                            onSubmitEditing={()=>{focusToNext(cat,parseInt(catIndex),skus,parseInt(sku_index),'1')}}
                                                            onChangeText={(val)=>{ onStockValChange(cat,skus,val,'Stock')}}
                                                            autoComplete='off'
                                                        />
                                                    </View>
                                                    
                                                </View>
                                            }
                                            </View>
                                        </View>
                                    )
                                }}/>
                            }
                        </View>
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView>
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{submitData()}}/> 
            </View>  
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
  }
  
  

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