import React,{useState,useEffect, memo, 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,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, getDownloadJson1} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, AppVersion} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card} from 'react-native-paper';
import {AntDesign, Entypo, EvilIcons, Feather, FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import NoDataComponent from '../components/NoDataComponent';
import {SvgXml} from 'react-native-svg';
import MapIcon from '../assets/performics/map_icon.svg';
import CustomModal from '../components/CustomModal';
import { AppTables } from '../constants/tableConstants';
import { _checkLocationPermission } from '../components/geolocation';
import { getMethodName, METHODS } from '../constants/methodNames';


function ImageAuditStoreList(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 [processing, setProcessing] = useState(false);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isDataFound, setisDataFound] = useState(false);
  
    const [addstoreinfo, setAddStoreInfo] = useState([]);
  
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(()=>{
      getData();
      setLoaderTitle(ST.Loading+'...');
    },[])
  
  
    async function getData(){     
      setProcessing(true)   
      try {
        
        let allImageAuditStoreListData= await DownloadImageAuditStoreList();
        console.log('allImageAuditStoreListData',allImageAuditStoreListData);
        if(allImageAuditStoreListData.length>0){
            setAddStoreInfo(allImageAuditStoreListData);
            setProcessing(false);
            setisDataFound(true);
        }
        else{
            notify(ST.Nodatafound);
            setProcessing(false);
        }
  
      } catch (err) {
        setProcessing(false);
        console.log(err);          
      }        
    }
  
    async function DownloadImageAuditStoreList(){
        let downloadKey="Sup_ImageAuditStoreList";
        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
        const url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
        let data={
          Downloadtype:downloadKey,
          Username: loginDetails.UserId,
          Param1: '',
          Param2: '',
        };
  
        console.log(url,data);
        return await getDownloadJson1(url,data)
        .then(async(res)=>{  
          if (res[downloadKey]) {
            let data_arr = res[downloadKey] || []; 
            return data_arr;
          }
          else{
            return [];
          }        
        })
        .catch((err)=>{
          console.log('onPage Team error',err);
          return [];
        }); 
    }
  

    const StoreItem=memo((props)=>{
        const route = useRoute();
        const PageTheme=GetPageTheme(props.DarkMode,route.name);
        const customStyle=customStyles(props.DarkMode,route.name);
        const item=props.item;
        const ST=props.StaticText || {};

        console.log(item, "itemss---------->>>>>")
      
        return(
          <TouchableOpacity
                    style={customStyle.storel}
                    key={props.index} > 
                    <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_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_code}>
                          <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder,customStyle.storel_codeConAddr]}>
                            <Text style={customStyle.storel_codeLbl}>{ST.Address+':'}</Text>
                            <Text style={customStyle.storel_codeText}>{item.Address}</Text>
                          </View>                    
                          <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                            <Text style={customStyle.storel_codeLbl}>{ST.CityName+':'}</Text>
                            <Text style={[customStyle.storel_codeText,{width:'50%'}]}>{item.CityName}</Text>
                          </View>
                        </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.CoveredBy+':'}</Text>
                            <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.CoveredBy}</Text>
                          </View>
                        </View>
                      
                        {
                          <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10,customStyle.storel_usOp]}>
                            <TouchableOpacity  style={[customStyle.storel_usOpBtn]} onPress={()=>{}}>
                            <Image style={{ height:18,width :18 , resizeMode:'contain', tintColor:PageTheme.$accent_color}} source={require('../assets/icons/audit/audit.png')} />
                              <Text style={customStyle.storel_usOpBtnText}>{'Audit'}</Text>
                            </TouchableOpacity> 
                          </View>
                        }
                      </View>
                      
                    </View> 
          </TouchableOpacity>
        );
    });
   
   
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
         {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={'Image Audit Store List'} />
   
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
        // style={{width:'100%'}}
         style={[customStyle.roundScrollWrapper]}
         >
          <View style={[customStyle.pageContentWrapper]}>
          { !props.isDataDownloaded && <NoDataComponent {...props}/>}
          <View style={[customStyle.storelist_parentwrap]}>
          { isDataFound==false && 
            <View style={customStyle.noDataCon}>
              <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
            </View>
          }
           { addstoreinfo.length> 0  &&
             <View style={[customStyle.storel_Con, {paddingBottom:0}]} >
              <FlatList
              data={addstoreinfo}
              style={customStyle.listcon}
              initialNumToRender={4}
              contentContainerStyle={[customStyle.iteml_con]}
              renderItem={({ item, index, separators }) =>{
                return(
                  <StoreItem  {...props} item={item} />
                );
                }}
              /> 
            </View>
             }
          </View>
         </View>      
       </LinearGradient>       
       
      </Container>   
    ); 
  }
  


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