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, Alert, KeyboardAvoidingView, BackHandler, 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,getKPIFields,marktext1,marktext2} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, Fontisto, Ionicons, 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 CheckBox from '@react-native-community/checkbox';

import cameraImg from '../assets/performics/camera_front_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { ConfirmSaveAlert, ExitScreenAlert } from '../components/alert';
import CustomCamera from '../components/Camera';
import Accordion from 'react-native-collapsible/Accordion';
import DateTimePicker from '@react-native-community/datetimepicker';
import { createFalse } from 'typescript';
import CustomModal2 from '../components/CustomModal2';

function StockCat(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 [productCats, setProductCats] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);

    const [showAlert, setShowAlert] = useState(false);
    const [rerendermodal, setrerendermodal] = useState(0);
    
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    

    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);
        const willFocusSubscription = props.navigation.addListener('focus', () => {
            console.log('onfocus');
            getData(storeData1);
        });

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

    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [hasUnsavedChanges]);   
    
    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            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;
         
          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 from Master_Category c ${join} ${join2}  where mp.StateId='${StateId}' and mp.ChainId='${ChainId}' and mp.StoreTypeId='${StoreTypeId}' order by p.CategorySequence`;
            
            // let q2=` SELECT CATEGORY_ID as CategoryId,CATEGORY as CategoryName FROM ${AppTables.STOCKWITHCAT_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                console.log('cats len:',txnres2.rows.length)
                if(txnres2.rows.length>0){
                    let arr=[];
                    for(var i=0;i<txnres2.rows.length;i++){
                        let data =txnres2.rows.item(i);
                        let isDone=await isCatDone(storeData1,data);
                        data['isDone']=isDone;
                        arr.push(data);
                        if(i==txnres2.rows.length-1){
                            setProductCats(arr);
                            setProcessing(false);
                        }                                
                    }
                    
                }else{
                    setProcessing(false);
                }
            },function (txn2, txnerr) { console.log(txnerr);setProcessing(false); },);
            
            
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function isCatDone(storeData1,cat){
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
        return await new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {  
                let seletlist=`STOCK_UID,PRODUCT as ProductName,PRODUCT_ID as ProductId,BRAND as BrandName,BRAND_ID as BrandId,SUB_CATEGORY as SubCategoryName,SUB_CATEGORY_ID as SubCategoryId,MSL,STOCK,BACKROOM_STOCK,DAMAGED_STOCK,LOST_STOCK,EXPIRY_STOCK,IS_SKU_STOCK_PRESENT,NREXPIRY1_STOCK,NREXPIRY2_STOCK,NREXPIRY3_STOCK`;
                let sku_q=`SELECT ${seletlist} FROM ${AppTables.STOCKWITHCAT_DATA} WHERE STORE_ID='${StoreId}' and CATEGORY_ID='${cat.CategoryId}'    `;
                await txn.executeSql(sku_q,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        resolve(true);
                    }else{
                        resolve(false);
                    }
                },function (txn2, txnerr) { console.log(txnerr);resolve(false); },);
                
              });   
        }).catch((err)=>{
            console.log(err);
            return false;
        })
    }

    function gotoCatProducts(cat={}){
        props.navigation.navigate('StockWithCat',{'storeData':storeData,'menu':currentMenu,'isAdhoc':isAdhocScreen,'category':cat});
    }


    function _renderStocks(){
        return (
            <KeyboardAvoidingView style={[customStyle.keyba_view,customStyle.keyba_viewContent]} behavior="position" enabled   keyboardVerticalOffset={-100} >  
            <FlatList 
            data={productCats}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.prodCatsScroll} 
            style={customStyle.prodCatsScroll_Outer}
            renderItem={({item,index})=>{
                const cat=item;
                let isDone=item.isDone;
                return(
                    <View style={customStyle.opening_Stock_wrap}>
                        <View style={customStyle.opening_Stock_cat}>   
                            <TouchableOpacity activeOpacity={0.5} style={customStyle.opening_Stock_catHdr} onPress={()=>{gotoCatProducts(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>
                                {(item.isDone!=null && item.isDone==true) && <View style={[customStyle.stockCatDone_check]}><AntDesign color={'green'} size={23} name='checkcircle'/></View>}
                            </TouchableOpacity>  
                        </View>
                    </View>
                );
            }}
            />
            </KeyboardAvoidingView>   
        )
    }
    
    
   
    
  
    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}`}/>        
       
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper,customStyle.prodCatPageWrap]}>
          <View style={customStyle.prodCatsHdr}>
            <Text style={customStyle.prodCatsHdrText}>Product Categories</Text>
          </View>
          {Object.keys(storeData).length>0 &&     
            _renderStocks()
          }
           
         </View>      
       </LinearGradient> 
      </Container>   
    ); 
}

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