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,Animated, 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 {checkMDStockScreenExists, getDownloadJson,getKPIFields,marktext1,marktext2, validateNumber} 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, Entypo, Fontisto, 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, Q_MenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';

import DateTimePicker from '@react-native-community/datetimepicker';

function OrderStatus(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 ST=props.StaticText || {};
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [Orderlist, setOrderList] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);

    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;
        let bgRedirFlag=params.redirect || false;
        let BgNavData=params.BgNavData || {};

        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);

        setCurrentMenu(menu1);
        if(bgRedirFlag==true && Object.keys(BgNavData).length>0){
            BgNavToOrderDetail(BgNavData,menu1)  
        }
            
        getData(storeData1,menu1);
        const willFocusSubscription = props.navigation.addListener('focus', () => {
            getData(storeData1,menu1);
          });
  
          return willFocusSubscription;

    }, []);

    function BgNavToOrderDetail(BgNavData,menu1){

        let {
            storeData,
            orderDetail}=BgNavData
            props.navigation.navigate("OrderDetail",{'storeData':storeData,'orderDetail':orderDetail,menu:menu1});
      }

    async function getData(storeData1,menu1){        
        try {   
          let {StoreId}=storeData1;

          await db.transaction(async function (txn) {   
            // let q=` SELECT Distinct OrderId,StorePO,SystemPO from PriviousVisit_Orders p Where p.StoreId ='${StoreId}'`;

           let q=` SELECT Distinct p.MID,p.InvoiceType, p.OrderId,p.StorePO,p.SystemPO,p2.ProductCount,(CASE WHEN o.FilledProdCount>0 THEN 1 ELSE 0 END) as IsDone from PriviousVisit_Orders p 
                    LEFT OUTER JOIN (select OrderId,MID,count(ProductId) as ProductCount from PriviousVisit_Orders GROUP BY OrderId,MID ) p2 on p.OrderId=p2.OrderId AND p.MID =P2.MID
                    LEFT OUTER JOIN (Select ORDER_ID,MID,count(ORDER_ID) as FilledProdCount from ORDER_STATUS where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' group by ORDER_ID) o on p.OrderId=o.ORDER_ID AND p.MID =o.MID
                    Where p.StoreId='${StoreId}'`;
            
            await txn.executeSql(q,[],async function (txn2, txnres) { 
                console.log('inputs found check',q);
                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);
                        let OrderId=data.OrderId || ""
                        // let q2=` SELECT * FROM ${AppTables.ORDERSTATUS} p WHERE p.ORDER_ID ='${OrderId}' and VISIT_DATE='${d2}'`;
                        // await txn.executeSql(q2,[],async function (txn2, txnres) { 
                        //     console.log('inputs found check',q);
                        //     if(txnres.rows.length>0){ 
                        //         console.log("OrderId is found -----",OrderId)
                        //         data["IsDone"]=true;
                        //     }else{data["IsDone"]=false;} },function (txnE,txnerr) { console.log(txnerr);},);
                        arr.push(data);
                        if(i==txnres.rows.length-1){
                            setOrderList(arr);
                            setProcessing(false);
                        }
                    }
                }else{
                    setProcessing(false);
                }
                
            },function (txnE,txnerr) { console.log(txnerr); setProcessing(false); },);

          });          
        } catch (err) {
          console.log(err);  
          setProcessing(false);        
        }        
    }
    
    async function get_to_store_details(item){
        props.navigation.navigate("OrderDetail",{storeData:storeData,orderDetail:item,menu:currentMenu});
    }
 
    function _render_PresentQ(item,index){
       
        return (
            <TouchableOpacity
                style={customStyle.storel}
                key={index}          
                onPress={() => {get_to_store_details(item)}}> 
                <View style={customStyle.storel_card_outer}> 
                    {/* <View style={customStyle.storel_card}>
                        <View style={customStyle.storel_card_content}>
                        <Text style={customStyle.storel_card_title}>{item.StoreName}</Text>
                        </View>                  
                    </View> */}
                    <View style={customStyle.storel_details}>
                        <View style={customStyle.storel_code}>
                        <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                            <Text style={customStyle.storel_codeLbl}>{'Order Id:'}</Text>
                            <Text style={customStyle.storel_codeText}>{item.OrderId}</Text>
                        </View>                    
                        </View>
                        <View style={customStyle.storel_code}>                    
                        <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                            <Text style={customStyle.storel_codeLbl}>{'Store PO:'}</Text>
                            <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.StorePO}</Text>
                        </View>
                        </View>
                        <View style={customStyle.storel_code}>                    
                        <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                            <Text style={customStyle.storel_codeLbl}>{'System PO:'}</Text>
                            <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.SystemPO}</Text>
                        </View>
                        </View>
                        <View style={customStyle.storel_code}>                    
                        <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                            <Text style={customStyle.storel_codeLbl}>{'Product Count:'}</Text>
                            <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.ProductCount}</Text>
                        </View>
                        </View>
                    </View>
                    { console.log("OrderId is found ----2-",item.IsDone)}
                    {item.IsDone ==true &&
                        <View style={customStyle.OrderStatus_Done}><AntDesign color={'green'} size={30} name='checkcircle'/></View>
                    } 
                </View> 
            </TouchableOpacity>
        );
    }
    
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props}showaddstore={true}  title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>            
        <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 &&
                <ScrollView contentContainerStyle={[customStyle.geotag_scroll]} style={{}}>            
                    <View style={customStyle.ImageTypesLHd}>
                        <Text  style={customStyle.ImageTypesLHdText}>{"Order Status"}</Text>
                    </View>
                    {Orderlist.map((item,index)=>{
                        return _render_PresentQ(item,index)
                    })
                    }
                </ScrollView>
            }
            {/* <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={'Save'} onPress={()=>{submitData()}}/> 
            </View>   */}
         </View>      
        </LinearGradient> 
      </Container>   
    ); 
  }
  
  

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