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,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 { getAvailblQuery, getIfAvlbl, getIfKPIDone, getQuery, Q_MenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { uploadAllImages, uploadStoreStatus } from '../constants/uploadData';
import { PrimaryTheme } from '../styles/Themes';
import NetworkStatusBar from '../components/NetworkStatusBar';
import * as RNFS from 'react-native-fs';

import CameraImg2 from '../assets/performics/camera_icon.svg';
import CustomCamera from '../components/Camera';
import NoAttendance from '../components/NoAttendance';
import ImageViewer from 'react-native-image-zoom-viewer';
import ImageWithLoader from '../components/ImageWithLoader';

function Album(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(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [albumImages, setAlbumImages] = useState([]);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [zoomImageIndex, setZoomImageIndex] = useState(0);
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [EmpData, setEmpData] = useState([]);
    const [storeData, setStoreData] = useState([]);
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const zoomView=useRef(null);

    
    useEffect(() => { 
        setLoaderTitle(ST.Loading+'...');
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let isAdhoc=params.isAdhocScreen || false;
        let empData1=params.empData || {};

        setIsAdhocScreen(isAdhoc);
        setEmpData(empData1);
        setStoreData(storeData1);

        getData(storeData1);
    }, []);


    async function getData(storeData1){
        console.log("storeData itemmmm",storeData1)
        console.log("storeData album",storeData1?.MerchandiserId)
        try {
            db.transaction(async function (txn) {        
                // get data with stores
                
                let sqlstmnt1 =`select * from Sup_Album where StoreId='${storeData1.StoreId}'`;
                // if(storeData1.MerchandiserId == '0') {
                //   sqlstmnt1 =`select * from Sup_Album where StoreId='${storeData1.StoreId}'`;
                // }else {
                //   sqlstmnt1 =`select * from Sup_Album where StoreId='${storeData1.StoreId}' and EmpId='${storeData1.MerchandiserId}'`;
                // } // commented suggested by vinay sir .
                
                console.log("sqlstmnt1=======",sqlstmnt1)
                await txn.executeSql(sqlstmnt1,[],async function (txn1, txnres) {
                    
                    if(txnres.rows.length>0){
                        let AllAlbumImages=await get_albumData(txnres);
                        setAlbumImages(AllAlbumImages);
                        setProcessing(false);                
                    }
                    else{
                        let AllAlbumImages=await DownloadAlbum(storeData1);
                        if(AllAlbumImages.length>0){
                            setAlbumImages(AllAlbumImages);
                            setProcessing(false);      
                        }
                        else{
                            notify('No data found');
                            setProcessing(false);        
                        }
                    }
                },function (txn1, txnerr) {console.log(txnerr);setProcessing(false);},);
            });
        } catch (err) {console.log(err);}
            
    }
    

    async function get_album(storeData1){        
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {        
                // get data with stores
                let sqlstmnt1 =`select * from Sup_Album where StoreId='${storeData1.StoreId}'  `;
                await txn.executeSql(sqlstmnt1,[],async function (txn1, txnres) {
                    if(txnres.rows.length>0){
                        let AllAlbumImages=await get_albumData(txnres);
                        resolve(AllAlbumImages);
                    }
                    else{
                        resolve([]);
                    }
                },function (txn1, txnerr) {console.log(txnerr);resolve([]);},);
            });
        }).catch((err)=>{
            console.log('err:',err);
            return [];
        });
    } 

    async function get_albumData(txnres){
        return new Promise((resolve,reject)=>{
            if(txnres.rows.length>0){
                let arr=[],images=[];
                for(var i=0;i<txnres.rows.length;i++){
                    let data=txnres.rows.item(i);
                    data.imgIndex=i;
                    arr.push(data);                            

                    let imgObj={imgIndex:i,url: data.ImageUrl, props: {}}
                    images.push(imgObj);
                    if(i==(txnres.rows.length-1)) {
                        setZoomImageUrl(images);
                        resolve(arr);
                    }
                }                        
            }
            else{
                resolve([]);
            }
        }).catch((err)=>{
            console.log('err:',err);
            return [];
        });
    }

    async function DownloadAlbum(storeData1){
      let downloadKey="Sup_Album";
      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: storeData1.StoreId,
        Param2: '',
      };

      console.log(url,data);
      return await getDownloadJson1(url,data)
      .then(async(res)=>{  
        if (res.Sup_Album) {
          let data_arr = res.Sup_Album || [];     
          console.log("data_arr===",data_arr)     
          let isInserted=await InsertAlbum(data_arr,storeData1);
         console.log("isInserted===",isInserted)
          if(isInserted){
            let AllImgs=await get_album(storeData1);  
            return AllImgs;
          }
          else{
            return [];
          }
        }
        else{
          return [];
        }        
      })
      .catch((err)=>{
        console.log('onPage Team error',err);
        return [];
      }); 
    }

    async function InsertAlbum(data_arr,storeData1){
        return new Promise((resolve,reject)=>{
            var values=[];
            data_arr.map((data_obj)=>{  
              let {Srno,EmpId,StoreId,KPI,LastMerchandisedDate,ImageUrl}=data_obj;
              values.push(` ('${Srno}','${EmpId}', '${StoreId}', '${KPI}', '${LastMerchandisedDate}', '${ImageUrl}')`);
            });
            
            var all_vals=values.join(',');
            var sql_stmnt=`INSERT INTO Sup_Album(Srno,EmpId,StoreId,KPI,LastMerchandisedDate,ImageUrl)
            values ${all_vals}`;         
                  
            db.transaction(function(txn) {
              // delete all today data
              txn.executeSql(`delete from Sup_Album where 1=1`,[],function(txn1,txnres){
                  // insert or refresh all today data
                  txn.executeSql(sql_stmnt,[],function(txn1,txnres){
                      console.log('Sup_Album added');
                      resolve(true);
                  },function(txn1,txnerr){resolve(false);});                         
              },function(txn1,txnerr){resolve(false);});                                        
            }); 
        }).catch((err)=>{
            console.log('err',err);
            return false;
        })
    }

   
   

    async function openZoomImage(item){
        let index=zoomImageUrl.findIndex(i=> i.imgIndex== item.imgIndex);
        console.log('index:',index,item)
        if(index>=0) setZoomImageIndex(index)
        setShow_zoomImage(true);
    }


    function _renderHeader(currentIndex){        
        return(
            <View style={customStyle.album_ZOOM_topBar}>
                <Text style={customStyle.album_ZOOM_indicator}>{`${(currentIndex+1)}/${zoomImageUrl.length}`}</Text>
                <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={()=>{console.log('tsth');setShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#000'} size={24}/>
                </TouchableOpacity>            
            </View> 
        )
    }

    // console.log("albumImages",albumImages)
  
    return ( 
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
            <CustomHeader {...props} title={'Album'} />
            {!show_zoomImage &&
            <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.ImageTypesPageWrap]}>
                    <View style={[customStyle.storel,customStyle.storeInfo_wrap]}>

                    <View style={customStyle.storel_card_outer}> 
                    <View style={customStyle.storel_card}>
                        <View style={customStyle.storel_card_content}>
                        <Text style={customStyle.storel_card_title}>{storeData.StoreName}</Text>
                        <View style={customStyle.storel_card_subtitle}>
                            <Text style={customStyle.storel_card_subtitleTxt}>{storeData.StoreType}</Text>
                        </View>
                        </View>                  
                    </View>
                    <View style={customStyle.storel_details}>
                        <View style={customStyle.storel_code}>
                        <View style={[customStyle.storel_codeCon,customStyle.storel_codeBorder]}>
                            <Text style={customStyle.storel_codeLbl}>{ST.StoreId+':'}</Text>
                            <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                        </View>                    
                        <View style={[customStyle.storel_card_outer]}>
                            <Text style={customStyle.storel_codeLbl}>{ST.StoreCode+':'}</Text>
                            <Text style={customStyle.storel_codeText}>{storeData.StoreCode}</Text>
                        </View>
                        </View>
                    </View>                
                    </View> 

                    </View>

                  
                    <FlatList
                    data={albumImages}
                    style={customStyle.listcon}
                    contentContainerStyle={customStyle.iteml_con}
                    renderItem={({ item, index, separators }) =>{
                        return(
                        <View  style={customStyle.alumbl} key={index}>
                            <Text style={customStyle.alumbl_topText}>{(item.StoreName?item.StoreName+' ':'')+'('+item.KPI+')'}</Text>
                            <TouchableOpacity activeOpacity={0.5} style={customStyle.alumbl_imgCon}  onPress={()=>{openZoomImage(item)}}>
                               {/* {item.ImageUrl && <Image style={customStyle.alumbl_img} source={{uri:item.ImageUrl}}/>} */}
                               {item.ImageUrl && <ImageWithLoader style={customStyle.alumbl_img} uri={item.ImageUrl} />}
                            </TouchableOpacity>
                            {console.log("item.LastMerchandisedDate",item.ImageUrl)}
                            <Text style={customStyle.alumbl_bottomText}>{'Captured on : '+moment(item.LastMerchandisedDate,"MM/DD/YYYY").format('MM/DD/YYYY')}</Text>
                        </View>
                        );
                    }}
                    />
                </View>      
            </LinearGradient>}       
            {show_zoomImage && 
                    <View style={customStyle.album_ZOOM_wrap}>
                        <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl} 
                        renderHeader={_renderHeader} index={zoomImageIndex}  renderIndicator={()=>null}
                        />
                    </View>        
            }
        </Container>  
    ); 
  }
  


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