import React,{useState,useEffect, memo,useCallback} from 'react';
import Container from '../components/container';
import { useRoute,useFocusEffect } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,TouchableHighlight,Platform,PermissionsAndroid,FlatList} 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,AddStore, checkRange, UploadData2, UploadData, UpdateStoreStatus, getKPIS, marktext1, marktext2, UploadFormData, validateNumber, ValidateEmail} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, AppVersion, common_ImagePath, baseurl} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, EvilIcons, Feather, FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons,FontAwesome5} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { _checkLocationPermission } from '../components/geolocation';


import CustomCamera from '../components/Camera';
import CustomModal from '../components/CustomModal';



function KycStoreList(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);

    const [loaderTitle, setLoaderTitle] = useState("Loading...");
    const [processing, setProcessing] = useState(false);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [isBeatPlan, setIsBeatPlan] = useState(false);
    const [storeData, setStoreData] = useState({});

    const [PrevStoreList, setPrevStoreList] = useState([]);
    const [StoreReason, setStoreReason] = useState([]);
    const [storeList, setStoreList] = useState([]);
    const [searchedItem, setSearchedItem]= useState('');
    const [globalStorelist, setGlobalStorelist] = useState([]);
    

    const [AllFormData, setAllFormData] = useState({});
    const [showCamera, setShowCamera] = useState(false);
   
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);

    const [IsEnableSubmit,setIsEnableSubmit] = useState(false);

    const [isNonMerchan, setIsNonMerchan] = useState(false);
    const [isNonProg, setIsNonProg] = useState(false);
    const [filtervalue, setFilterValue] = useState({});
    const [showAlert, setShowAlert] = useState(false);
    const [EntryAllow, setEntryAllow] = useState(false);

    const [isDisable, setDisable] = useState(false);


    
    let d1=new Date();
    let today=moment(d1).format('MM/DD/YYYY');
    

    useFocusEffect(
      useCallback(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        getData(); // this will reload the store list every time screen is focused
        let st2=Object.assign({'test':'1'} , storeData1);
        setAllFormData(st2); //Assigning current Store Data to FormData to be filled or changed
      }, [])
    );


    async function getData(storeData1) {
      console.log("Function called with date:", today);
    
      try {
        setLoaderTitle(ST.Loading + '...');
        setProcessing(true);
    
        db.transaction((txn) => {
          console.log("Transaction started ✅");
    
         let loadQuery = `SELECT distinct K.*,ifnull(T.STORE_ID,0)as Status from KYC_StoreList K left join (SELECT * from KYC_INFO Where VISIT_DATE = ?)as T on K.StoreId = T.STORE_ID Where K.VisitDate =? `
         // let loadQuery = `SELECT * FROM KYC_StoreList WHERE VisitDate = ?`;
          console.log("Executing query:", loadQuery);
    
          txn.executeSql(
            loadQuery,
            [today,today],
            (txn2, txnres) => {
              console.log('Query success, rows:', txnres.rows.length);
              let stores = [];
    
              for (let i = 0; i < txnres.rows.length; i++) {
                stores.push(txnres.rows.item(i));
              }

              console.log("Loaded stores:", stores);
       
              setStoreList(stores);
              setGlobalStorelist(stores);
              setProcessing(false);
              console.log("Loaded products:", storeList);
            
            },
            (txnE, txnerr) => {
              console.log('SQL Error:', txnerr);
              setProcessing(false);
            }
          );
        });
    
      } catch (err) {
        console.log('Catch block error:', err);
        setProcessing(false);
      }
    }
    


    function _render_Alert(){
        return (
          <CustomModal 
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={'Do you really want to save data?'}
            showModal={showAlert}
          >
           
          </CustomModal>
        )
      }
      async function validate(){
        let isValid=true;
                
        await Promise.all(
            PrevStoreList.map(async (item,index) => {
            if(isValid==true){
                if(!Boolean(item.Reason) && item.ReasonId== null || item.ReasonId==''){
                    notify('Please select reason for store Id '+item.StoreId,'SHORT');
                    isValid=false;
                }
            }
            })
        );

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

  

    function FilterStores(searchedQry){
      searchedQry=searchedQry.toLowerCase();
      console.log('searchedQry',searchedQry);
    //  let {storeList}=state;
      let arr=[]
      if(searchedQry!=null && searchedQry!=''){
        globalStorelist.map((item,index)=>{
          let {StoreName,StoreId,StoreCode}=item;
          StoreId=StoreId+'';
          if(StoreName.toLowerCase().includes(searchedQry) || StoreCode.toLowerCase().includes(searchedQry) || StoreId.includes(searchedQry)){
            arr.push(item);
          }
        });
      }
      else{
        arr=globalStorelist;
      }
      setStoreList(arr);
      setrerenderdata(!rerenderdata)
    }

  

    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}> 
      {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}      
        <CustomHeader {...props} title={"KYC Store List"} />
        {_render_Alert()}
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: Store Profile'} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        <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.storel_searchbar}>
                       <TextInput 
                         style={[customStyle.storel_searchInput]}
                         placeholder={ST.Searchby+` ${ST.StoreName}, ${ST.StoreId}, ${ST.StoreCode}`}
                         autoComplete='off' 
                         placeholderTextColor={PageTheme.$placeholder_color} 
                         value={searchedItem}
                         onChangeText={(val)=>{setSearchedItem(val); FilterStores(val)}}
                       />
                       <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem)}}>
                         <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
                       </TouchableOpacity>
                   </View>
           
            <ScrollView  
              style={customStyle.STp_ContentOuter}
              contentContainerStyle={customStyle.STp_ContentInner}
            >
            {console.log("storelist--->",storeList)}
              {rerenderdata==rerenderdata && storeList?.map((item,index)=>{
                return(

                    <TouchableOpacity
                     key={index}
                     style={[customStyle.STp_Card]}

                    onPress={() => {
                        if (item.Status != 0) {
                          notify("You have already uploaded data for this store.");
                        } else {
                           props.navigation.navigate('KycForm', { storeId: item.StoreId });
                        }
                      }}>
                        <View style={[customStyle.STp_card_outer, ]}> 
                        <View style={[customStyle.STp_storeDetails,]}>
                            <View style={customStyle.storel_code}>
                            <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder,customStyle.storel_codeConAddr]}>
                                <Text style={customStyle.storel_codeLbl}>{ST.StoreId+':'}</Text>
                                <Text style={customStyle.storel_codeText}>{item.StoreId}</Text>
                            </View>                    
                            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                <Text style={customStyle.storel_codeLbl}>{ST.StoreType+':'}</Text>
                                <Text style={[customStyle.storel_codeText,{width:'50%'}]}>{item.StoreType}</Text>
                            </View>
                            </View>
                            <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>                    
                            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                <Text style={customStyle.storel_codeLbl}>{ST.StoreCode+':'}</Text>
                                <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.StoreCode == "undefined"?"":item.StoreCode}</Text>
                            </View>
                            </View>
                            <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>                    
                            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                <Text style={customStyle.storel_codeLbl}>{'Store Name:'}</Text>
                                <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.StoreName}</Text>
                            </View>
                            </View> 
                            <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>                    
                            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                <Text style={customStyle.storel_codeLbl}>{'City Name:'}</Text>
                                <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.CityName}</Text>
                            </View>
                            </View>        
                            <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.storel_codeBorderBottom,customStyle.mt10]}>                    
                            <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                <Text style={customStyle.storel_codeLbl}>{'Address:'}</Text>
                                <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.Address}</Text>                               
                            </View>
                            </View>           
                            
                        </View>
 

                          { item.Status != 0 &&
                            <View style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: 10, width: '100%', marginTop: 20 }}>
                              {/* <MaterialCommunityIcons name="check-all" size={20} color="green" style={{ marginRight: 5 }} /> */}
                              <Text style={[customStyle.sform_label3, { color: 'green', fontWeight: 'bold', marginTop: 0 }]}>Uploaded</Text>
                              <MaterialCommunityIcons name="check-all" size={20} color="green" style={{ marginLeft: 5 ,marginBottom: 6}} />
                            </View>
                          }
                             
                        </View> 
               
                    </TouchableOpacity>
                )
                })
            }
            </ScrollView>

            {/* <View style={customStyle.SChk_BtnWrapFlex}>              
              <View style={[customStyle.SChk_BtnCol,customStyle.SChk_BtnCol2]}>
                  <View style={[customStyle.SChk_Btn]}>
                     <GradientButton {...props} title={'Save'} onPress={()=>{submit()}}/> 
                  </View> 
              </View>
            </View>      */}
        </View>
       </LinearGradient>
      </Container>   
    ); 
  }
  


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