import React,{useState,useEffect} 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,KeyboardAvoidingView, Alert, Keyboard} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,marktext1,marktext2, UploadData2} 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 { getPostData2 } from '../components/downloadTasks';
import { getMethodName, METHODS, METHOD_KEYS } from '../constants/methodNames';

function WarehousePOSM(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 [currentWarehouse, setCurrentWarehouse] = useState({});
    const [isDataUploaded, setIsDataUploaded] = useState(false);
    const [AllWarehouses, setAllWarehouses] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    
    const [POSMStock, setPOSMStock] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [NodataFound, setNodataFound] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        let params=props.route.params? props.route.params:{};
        let wh=params.warehouse!=null?params.warehouse:{};
        let isUploaded=params.isUploaded!=null?params.isUploaded:false;
        setCurrentWarehouse(wh);
        setIsDataUploaded(isUploaded);
        
        getData(wh);
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
            return unsubscribe;
        };
    }, []);

    useEffect(() => {
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [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(warehouse){  
        
        let pdata = await getPostData2('Mapping_WarehouseCurrentPosmStock');
        let url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
        console.log(url,pdata);
        await fetch(url, {
            method: 'post',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(pdata),
        })
        .then(response => {
            return response.json();
        })
        .then(async(res) => {
            res = JSON.parse(res);
            if (res.Mapping_WarehouseCurrentPosmStock) {
                
                let isInserted= await insertWarehousePOSM(res);
                if(isInserted){
                    let arr=await getWarehousePOSM(warehouse);
                    if(arr.length>0){
                        setAllWarehouses(arr);
                        setNodataFound(false); 
                        // console.log('allwarehouses',arr);
                    }
                    else{
                        setAllWarehouses(arr);
                        setNodataFound(true); 
                        // console.log('allwarehouses',arr);
                    }
                    setProcessing(false);
                }
                else{
                    notify('Something went wrong! Cannot load warehouse POSM');
                    setAllWarehouses([]);
                    setNodataFound(false); 
                    setProcessing(false);
                }
                
            }
            else{  
                setAllWarehouses([]);
                setNodataFound(true); 
                setProcessing(false);
                console.log('allwarehouses no found');
            } 
           
            
        })
        .catch(err => {
            console.log('getProjectData error', err);
            setProcessing(false);
        });
    }


    async function insertWarehousePOSM(res){
        console.log('insertWarehousePOSM');
        return new Promise((resolve,reject)=>{
            let data_arr = res.Mapping_WarehouseCurrentPosmStock || [];          
            var values=[];
            data_arr.map((data_obj)=>{  
                let {WarehouseId, WarehouseName, POSMId, CurrentPosmStock}=data_obj;
                values.push(` ('${WarehouseId}','${WarehouseName}','${POSMId}','${CurrentPosmStock}')`);
            });

            console.log('insertWarehousePOSM len:',data_arr.length);

            

            var all_vals=values.join(',');
            var sql_stmnt=`INSERT INTO Mapping_WarehouseCurrentPosmStock(WarehouseId, WarehouseName,POSMId,CurrentPosmStock)
            values ${all_vals}`; 
            db.transaction(async function(txn) {
               

                await txn.executeSql(`delete from Mapping_WarehouseCurrentPosmStock where 1=1`,[],function(txn1,txnres){
                    // insert or refresh all today data
                    txn.executeSql(sql_stmnt,[],function(txn1,txnres){
                        resolve(true);
                        
                    },function(txn1,txnerr1){ console.log(txnerr1); resolve(false);});                         
                },function(txn1,txnerr1){ console.log(txnerr1); resolve(false);});                                        
            });  
          
        }).then((res)=>{return res})
        .catch((err)=>{
            console.log(err);
            return false;
        })
       
    }
    
    async function getWarehousePOSM(warehouse){
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {  
                let join_ustk2=' LEFT JOIN User_CurrentPosmStock u on pw.POSM_ID=u.PosmId ';
                let join2=' INNER join Mapping_WarehouseCurrentPosmStock wh on wh.POSMId=pw.POSM_ID and wh.WarehouseId=pw.WAREHOUSE_ID ';
                let join3=' INNER join Master_POSMDefinition p on p.PosmId=pw.POSM_ID ';
                let sellist2=` IFNULL(( select SUM(IFNULL(u2.POSM_QTY,0))  from  ${AppTables.POSM_WAREHOUSE} u2 where u2.POSM_ID=pw.POSM_ID and u2.VISIT_DATE='${d2}' ),0) as TodayPOSMQty,IFNULL(( select SUM(IFNULL(u3.POSM_QTY,0))  from  ${AppTables.POSM_HDR_DATA} u3 where u3.POSM_ID=pw.POSM_ID and u3.VISIT_DATE='${d2}' ),0) as TodayUsedPOSMQty,IFNULL(u.TotalPosmIn,0) as TotalPosmIn,IFNULL(u.TotalPosmOut,0) as TotalPosmOut`;
                let q2=`SELECT Distinct pw.POSM_ID as POSMId,p.POSMName,wh.CurrentPosmStock,pw.POSM_QTY as POSMQty,${sellist2} from ${AppTables.POSM_WAREHOUSE} pw ${join2} ${join3} ${join_ustk2} where pw.WAREHOUSE_ID='${warehouse.WarehouseId}' and pw.VISIT_DATE='${d2}'  order by p.POSMName`; 
                
                let join=' INNER join Mapping_WarehouseCurrentPosmStock wh on wh.POSMId=p.PosmId ';
                let join_ustk1=' LEFT JOIN User_CurrentPosmStock u on p.PosmId=u.PosmId ';
                // let join_ustk2=` LEFT JOIN ${AppTables.POSM_WAREHOUSE} u2 on p.PosmId=u2.POSM_ID and u2.VISIT_DATE='${d2}'`;
                // let join_ustk3=` LEFT JOIN ${AppTables.POSM_HDR_DATA} u3 on p.PosmId=u3.POSM_ID and u3.VISIT_DATE='${d2}'`;
                let sellist=` IFNULL(( select SUM(IFNULL(u2.POSM_QTY,0))  from  ${AppTables.POSM_WAREHOUSE} u2 where u2.POSM_ID=p.PosmId and u2.VISIT_DATE='${d2}' ),0) as TodayPOSMQty,IFNULL(( select SUM(IFNULL(u3.POSM_QTY,0))  from  ${AppTables.POSM_HDR_DATA} u3 where u3.POSM_ID=p.PosmId and u3.VISIT_DATE='${d2}' ),0) as TodayUsedPOSMQty,IFNULL(u.TotalPosmIn,0) as TotalPosmIn,IFNULL(u.TotalPosmOut,0) as TotalPosmOut`;
                let q=`SELECT Distinct p.PosmId as POSMId,p.POSMName,wh.CurrentPosmStock,${sellist} from Master_POSMDefinition p ${join} ${join_ustk1} where wh.WarehouseId='${warehouse.WarehouseId}' order by p.POSMName`;
              

                console.log(q2);
                
                await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                    console.log('data added posm:',txnres2.rows.length);
                    
                    if(txnres2.rows.length>0){
                        let arr=[],arr2=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);

                            if(i==0) console.log('data:',data);
                            let userTotalPOSMQtyIn=parseInt(data.TodayPOSMQty)+parseInt(data.TotalPosmIn);
                            let userTotalPOSMQtyOut=parseInt(data.TodayUsedPOSMQty)+parseInt(data.TotalPosmOut);
                            
                            let UserPOSMQtyAvl=(parseInt(userTotalPOSMQtyIn)-parseInt(userTotalPOSMQtyOut));
                            
                            let obj={'POSMId':data.POSMId,'POSMQty':(data.POSMQty!=null?data.POSMQty:''),'UserPOSMQtyAvl':UserPOSMQtyAvl};
                            arr.push(data);
                            arr2.push(obj);
                            if(i==txnres2.rows.length-1){
                                setPOSMStock(arr2);
                                resolve(arr);
                            }                                
                        }
                    }
                    else{
                        console.log(q);
                        await txn.executeSql(q,[],async function (txn2, txnres3) { 
                            console.log('data loaded posm:',txnres3.rows.length);
                            if(txnres3.rows.length>0){
                                let arr=[],arr2=[];
                                for(var i=0;i<txnres3.rows.length;i++){
                                    let data =txnres3.rows.item(i);
                                    let userTotalPOSMQtyIn=parseInt(data.TodayPOSMQty)+parseInt(data.TotalPosmIn);
                                    let userTotalPOSMQtyOut=parseInt(data.TodayUsedPOSMQty)+parseInt(data.TotalPosmOut);
                                    let UserPOSMQtyAvl=(parseInt(userTotalPOSMQtyIn)-parseInt(userTotalPOSMQtyOut));
                                   
                                    let obj={'POSMId':data.POSMId,'POSMQty':'','UserPOSMQtyAvl':UserPOSMQtyAvl};
                                    arr.push(data);
                                    arr2.push(obj);
                                    
                                    if(i==txnres3.rows.length-1){
                                        setPOSMStock(arr2);
                                        resolve(arr);
                                    }                                
                                }
                            }
                            else{
                                resolve([])
                            }
                        },function (txnE,txnerr) { console.log(txnerr); resolve([]) },);
                    }
                },function (txnE,txnerr) { console.log(txnerr);  resolve([]) },);

            });
        }).then((res)=>{return res})
        .catch((err)=>{
            console.log(err);
            return [];
        })
       
    }

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

    async function saveData(){
        setHasUnsavedChanges(false);
        setShowAlert(false);
        setLoaderTitle('Saving Data...');
        setProcessing(true);
        
        let obj=await insertPOSMData();
        if(obj.isInserted==true){
            setLoaderTitle('Uploading Data...');
            uploadPOSMData(obj.uploadData);
        }
        else{
            notify('Something went wrong while saving data!');
            setProcessing(false);
        }
    }

    async function uploadPOSMData(uploadData=[]){
        const url=props.ApiUrl+METHOD_KEYS.WAREHOUSE_POSM_OUTWARD;

        let postData={};
        postData['OutwardPosmJson']=uploadData;
        postData['UserId']=props.UserId;

        console.log(url,postData)
        await UploadData2(url,postData)
        .then(async(res)=>{
            console.log('res:',res);
            if(res.WarehousePosmOutward!=null){
                notify('Data uploaded successfuly!');
                let isStatusUpdated=await updatePOSMDatauploaded();
                if(!isStatusUpdated){  notify('Cannot update status!'); }
                setProcessing(false);
                props.navigation.goBack();
            }
            else{
                notify('Cannot upload data!');
                setProcessing(false);
            }
            
        })
        .catch((err)=>{
            console.log(err);
            notify('Cannot upload data!');
            setProcessing(false);
        });
        
    }

    async function insertPOSMData(){
        let defData={isInserted:false,uploadData:[]}
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {   
                var values='',data=[];
                
                for(let i=0;i<AllWarehouses.length;i++){
                    let item=AllWarehouses[i];
                    let {POSMId, POSMName,CurrentPosmStock}=item;
                    let transId=props.UserId+POSMId+moment().format('DDMMYYYYHHmmss');

                    values+=values!=''?' , ':'';
                    let allData=POSMStock;
                    const skud_index=allData.findIndex(ci=>ci.POSMId==item.POSMId);
                    const skud=skud_index>=0?(allData[skud_index] || {}) : {};
                    let POSMQty=skud['POSMQty']!=null && skud['POSMQty']!=''?skud['POSMQty']:'0';
                    
                    
                    values+=` ('${transId}','${d2}','${currentWarehouse.WarehouseId}','${POSMId}','${CurrentPosmStock}','${POSMQty}','S','${d2}') `;
                
                    

                    // upload data :
                    let obj={}; 
                    obj['UserId']=props.UserId;
                    obj['WarehouseId']=currentWarehouse.WarehouseId;
                    obj['VisitDate']=d2;
                    obj['POSMId']=POSMId;
                    obj['OutwardQty']=POSMQty;
                    obj['TranId']=transId;

                    data.push(obj);
                
                }

                console.log('values:',values);
                
                
                let q=`INSERT INTO ${AppTables.POSM_WAREHOUSE } (TRANSACTION_ID,VISIT_DATE,WAREHOUSE_ID,POSM_ID,WAREHOUSE_STOCK,POSM_QTY,STATUS,ADDED_DATE) VALUES ${values}`
                
                await txn.executeSql(`Delete from  ${AppTables.POSM_WAREHOUSE } where WAREHOUSE_ID='${currentWarehouse.WarehouseId}' `,[],async function (txn2, txnres2) { 
                    console.log('POSM warehouse data deleted')
                    await txn.executeSql(q,[],async function (txn2, txnres) { 
                        defData['uploadData']=data;
                        defData['isInserted']=true;
                        resolve(defData);
                    },function (txnE,txnerr) { console.log(txnerr); resolve(defData); },);
                },function (txnE,txnerr) { console.log(txnerr); resolve(defData); },);

               
            });   
          
        }).then((res)=>{return res})
        .catch((err)=>{
            console.log(err);
            return defData;
        })
    }

    async function updatePOSMDatauploaded(){
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {   
                let q=`update ${AppTables.POSM_WAREHOUSE } set STATUS='U' where WAREHOUSE_ID='${currentWarehouse.WarehouseId}'  `
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    resolve(true);
                },function (txnE,txnerr) { console.log(txnerr); resolve(false); },);
            });   
          
        }).then((res)=>{return res})
        .catch((err)=>{
            console.log(err);
            return false;
        })
    }

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


    async function validate(){
        let isValid=true;
        var i=0,j=0;
        await Promise.all(
            AllWarehouses.map(async (item,index) => {
                if(isValid){
                    let skuData=POSMStock.find(ci=>ci.POSMId==item.POSMId) || {};
                    let POSMQty1=skuData['POSMQty']!=null && skuData['POSMQty']!=''?skuData['POSMQty']:'0';

                    // if(skuData.POSMQty!==0 && (skuData.POSMQty==null)){
                    //     notify('Please enter POSM quantity for '+item.POSMName,'SHORT');
                    //     isValid=false;
                    // }else 
                    if(parseInt(POSMQty1)>parseInt(item.CurrentPosmStock)){
                        notify('POSM quantity should not be greater than the current warehouse POSM Stock for '+item.POSMName,'LONG');
                        isValid=false;
                    }else{
                       
                    }
                }
            })
        );

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

    function onStockValChange(item,val,key,type=''){
        if(type=='numeric' && val!=''){
            const regex = new RegExp(/^\d+$/);
            let isNUmeric=regex.test(val);
            if(!isNUmeric){
                notify('Please enter whole numbers only','SHORT');
                return;
            }
        }
        let allData=POSMStock;
        let defData={'POSMId':item.POSMId};
        const skud_index=allData.findIndex(i=>i.POSMId==item.POSMId);
        const skud=skud_index>=0?(allData[skud_index] || defData) : defData;
        skud[key]=val;

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

    function _render_Alert(){
        return (
          <CustomModal 
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={'Do you really want to save and upload 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}showaddstore={true}  title={'Warehouse POSM'}/>
        {_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]}>
            <View style={[customStyle.warehouseHd,{marginBottom:0}]}>
                <Text  style={customStyle.warehouseHdText}>{`Warehouse : ${currentWarehouse.WarehouseName}`}</Text>
            </View>
          { Object.keys(AllWarehouses).length>0 &&    
            
           <KeyboardAvoidingView style={[customStyle.warehousekeyba_view]} behavior="position" enabled   keyboardVerticalOffset={-100} >  
            {/* <View style={{paddingHorizontal:10,height:'100%',width:'100%'}}> */}
            <FlatList 
                data={AllWarehouses}
                contentContainerStyle={[customStyle.warehousePOSM_scroll]} 
                style={[customStyle.warehousePOSM_scrollOuter]}
                extraData={rerenderdata}
                renderItem={({item,index})=>{
                    
                    let thisDataIndex=POSMStock.findIndex(i=>i.POSMId==item.POSMId);
                    let thisData=thisDataIndex>=0?(POSMStock[thisDataIndex] || {}):{};
                    let POSMQty=thisData.POSMQty!=null?thisData.POSMQty:'';
                    let UserPOSMQtyAvl=thisData.UserPOSMQtyAvl!=null?thisData.UserPOSMQtyAvl:'0';
                   

                    return(
                        <View style={customStyle.openStk_prd_Con} key={'POSM_'+index}>
                            <Text style={customStyle.openStk_prd_name}>{item.POSMName}</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}>{`Warehouse POSM Stock : ${item.CurrentPosmStock}`}</Text>
                                </View>
                            </View>
                            <View style={[customStyle.openStk_prddetails2,customStyle.openStk_prd_borderB]}>
                                <View style={[customStyle.openStk_prdd_wrap]}>
                                    <Text style={customStyle.openStk_prdd_flabel}>{`User POSM Stock Available : ${UserPOSMQtyAvl}`}</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]}>{`POSM Quantity ${(isDataUploaded?' : ':'')}`}</Text>
                                        {!isDataUploaded && 
                                        <TextInput 
                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle]}              
                                            placeholder=""     
                                            autoComplete='off'       
                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                            value={POSMQty+''}
                                            keyboardType='number-pad'
                                            onChangeText={(val)=>{ onStockValChange(item,val,'POSMQty','numeric')}}
                                        />
                                        }
                                        {isDataUploaded && 
                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{POSMQty}</Text>
                                        }
                                    </View>
                                </View>
                            </View>
                        </View>
                    )
            }}/>
            {/* </View> */}
            </KeyboardAvoidingView>
            
            }
            {!isDataUploaded &&
            <View style={[customStyle.opening_Stock_btnWrap]}>
                {/* <GradientButton {...props} colors={(isDataUploaded?['#9e9e9e','#9e9e9e']:null)} title={'Upload'} textStyle={(isDataUploaded?{}:null)} activeOpacity={(isDataUploaded?1:null)}  onPress={()=>{(isDataUploaded?()=>{}:submitOpeningStock())}}/>  */}
                <GradientButton {...props}  title={'Upload'}  onPress={()=>{submitOpeningStock()}}/> 
            </View>  
            }
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

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