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} 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 { getMethodName, METHODS } from '../constants/methodNames';
import { getPostData, getPostData2 } from '../components/downloadTasks';

function Warehouse(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 [AllWarehouses, setAllWarehouses] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
    
    const [NodataFound, setNodataFound] = useState(false);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        
       getData();
       const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
       const willFocusSubscription = props.navigation.addListener('focus', () => {
        getData();
      });

        return function cleanup() {
          willFocusSubscription();
            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(){  
        
        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 data_arr = res.Mapping_WarehouseCurrentPosmStock || [];  
                // let arr=[];
                // for(let i=0;i<data_arr.length;i++){
                //     let data=data_arr[i];
                    
                //     let windex=arr.findIndex(i=>i.WarehouseId==data.WarehouseId);
                //     if(windex<0){
                //       let wh_data=await getWarehouseStatus(data);
                //       console.log('wh_data:',wh_data);
                //       data.isUploaded=wh_data.STATUS=='U'?true:false;
                //       data.TotalPOSMQty=wh_data.total_posm_qty!=null?wh_data.total_posm_qty:0;
                //       arr.push(data);
                //     }

                //     if(i==data_arr.length-1){
                //         arr.sort((a,b)=> a.WarehouseName-b.WarehouseName);
                //         setAllWarehouses(arr);
                //         setNodataFound(false); 
                //         setProcessing(false);
                //         console.log('allwarehouses',arr);
                //     }
                // }

                let isInserted= await insertWarehousePOSM(res);
                if(isInserted){
                    let arr=await getWarehouses();
                    if(arr.length>0){
                      let narr=[];
                      for(let i=0;i<arr.length;i++){
                        let data=arr[i];
                        let wh_data=await getWarehouseStatus(data);
                        console.log('wh_data:',wh_data);
                        data.isUploaded=wh_data.STATUS=='U'?true:false;
                        data.TotalPOSMQty=wh_data.total_posm_qty!=null?wh_data.total_posm_qty:0;
                        narr.push(data);

                        if(i==arr.length-1){
                          console.log('alldata:',narr);
                          setAllWarehouses(narr);
                          setNodataFound(true); 
                          setProcessing(false);
                        }
                      }
                        // console.log('allwarehouses',arr);
                    }
                    else{
                        setAllWarehouses(arr);
                        setNodataFound(true); 
                        setProcessing(false);
                        // console.log('allwarehouses',arr);
                    }
                    
                }
                else{
                    notify('Something went wrong! Cannot load warehouse POSM');
                    setAllWarehouses([]);
                    setNodataFound(true); 
                    setProcessing(false);
                }
                
            }
            else{  
                setAllWarehouses([]);
                setNodataFound(true); 
                setProcessing(false);
                console.log('allwarehouses no found');
            } 
            
            
        })
        .catch(err => {
          console.log('set blank');
            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 getWarehouses(){
      return new Promise((resolve,reject)=>{
          db.transaction(async function (txn) {  

              
              let join=' INNER join Mapping_WarehouseCurrentPosmStock wh on wh.POSMId=p.PosmId ';
              let q=`SELECT Distinct wh.WarehouseId,wh.WarehouseName from Master_POSMDefinition p ${join} order by wh.WarehouseName`;
              await txn.executeSql(q,[],async function (txn2, txnres3) { 
                console.log('data loaded warehouses:',txnres3.rows.length);
                if(txnres3.rows.length>0){
                    let arr=[];
                    for(var i=0;i<txnres3.rows.length;i++){
                        let data =txnres3.rows.item(i);
                        console.log('data:',data);
                        arr.push(data);
                        if(i==txnres3.rows.length-1){
                            resolve(arr);
                        }                                
                    }
                }
                else{
                    resolve([])
                }
            },function (txnE,txnerr) { console.log(txnerr); resolve([]) },);

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

    async function getWarehouseStatus(item){
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) {  
            let q=`SELECT STATUS,SUM(POSM_QTY) as total_posm_qty from ${AppTables.POSM_WAREHOUSE} where WAREHOUSE_ID='${item.WarehouseId}' `;
            
            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                console.log('data added posm:',txnres2.rows.length);
                if(txnres2.rows.length>0){
                  let data =txnres2.rows.item(0);
                  // let status=data.STATUS;
                  // let total_posm_qty=data.TOTAL_POSM_QTY;
                  resolve(data);
                }
                else{
                  resolve({});
                }
            },function (txnE,txnerr) { console.log(txnerr); resolve({}); },);

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

    function gotoPage(item){
      // if(item.isUploaded==true){
      //   // notify('Data already uploaded for this warehouse!','LONG');
       
      // }
      // else{
        
        props.navigation.navigate('WarehousePOSM',{'warehouse':item,'isUploaded':item.isUploaded});
      // }
    }

    function _renderWarehouses(){
        return(
            <View style={customStyle.warehouseI_listcon}>
            <View style={customStyle.warehouseI_list}>
              {rerenderdata==rerenderdata && AllWarehouses.length>0 &&
                AllWarehouses.map((item,index)=>{ 
                    
                    return (
                        <TouchableOpacity style={[customStyle.warehouseI_Wrap]} key={index} onPress={()=>{gotoPage(item);}}>
                            <View style={[customStyle.warehouseI_prd]}>
                              <Text style={[customStyle.openStk_prd_name,customStyle.warehouseI_CheckBox_pName]}>{item.WarehouseName}</Text>
                            </View>
                            <View style={customStyle.warehouseI_Details}>
                              <View style={[customStyle.warehouseI_detBox]}>
                                <Text style={customStyle.warehouseI_detLbl}>Warehouse Id:</Text>
                                <Text style={customStyle.warehouseI_detText}>{item.WarehouseId}</Text>
                              </View>
                              { (item.isUploaded!=null && item.isUploaded==true) &&
                              <View style={{flexDirection:'row'}}>
                                {/* <View style={[customStyle.warehouseI_detBox,customStyle.mt5,customStyle.warehouseI_borderL]}>
                                  <Text style={customStyle.warehouseI_detLbl}>Warehouse Stock:</Text>
                                  <Text style={customStyle.warehouseI_detText}>{item.CurrentPosmStock}</Text>
                                </View> */}
                                <View style={[customStyle.warehouseI_detBox,customStyle.mt5]}>
                                  <Text style={customStyle.warehouseI_detLbl}>Taken POSM Qty:</Text>
                                  <Text style={customStyle.warehouseI_detText}>{item.TotalPOSMQty}</Text>
                                </View>
                              </View>
                              }
                            </View>
                            {(item.isUploaded!=null && item.isUploaded==true) && <View style={[customStyle.warehouseI_DoneCheck]}><AntDesign color={'green'} size={23} name='checkcircle'/></View>}
                        </TouchableOpacity>
                    )
                })
              }
            </View>
            </View>
        )
    }

  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={'Warehouses'}/>
        
        <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}>
                <Text  style={customStyle.warehouseHdText}>Warehouses</Text>
            </View>
          { Object.keys(AllWarehouses).length>0 &&
            <ScrollView contentContainerStyle={[customStyle.geotag_scroll]} style={{}}>   
              {_renderWarehouses()}  
            </ScrollView>
          }
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}
  
  

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