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, Alert,BackHandler, Animated, AppState, Keyboard} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';

import {notify} from '../components/notify';
import Geolocation from 'react-native-geolocation-service';
import moment from 'moment';
import {getDownloadJson,getKPIFields,markAlltexts,marktext1,marktext2, resizeImage, restore_ImageWithMetaData} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath,ImageFolderPath} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome, 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 * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import CameraImg from '../assets/performics/add_image.svg'

import { ConfirmSaveAlert, ExitScreenAlert } from '../components/alert';
import CustomCamera from '../components/Camera';
import ImageViewer from 'react-native-image-zoom-viewer';

function StoreImagesCap(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 [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [currentMenu, setCurrentMenu] = useState({});
    const [ImageType, setImageType] = useState({});
    const [AllImagesData, setAllImagesData] = useState([]);
    const [rerenderdata, setrerenderdata]= useState(0);
   
    const [showAlert, setShowAlert] = useState(false);
    const [showRemoveAlert, setShowRemoveAlert] = useState(false);
    const [toRemoveIndex, setToRemoveIndex] = useState(0);
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const showCameraRef = useRef(false);
    const [getImageProps,setGetImageProps]= useState({});
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const show_zoomImageRef = React.useRef(false);
    const [refImageIndex, setrefImageIndex] = useState(0);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [ImgCount, setImgCount] = useState(0);

    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(true);

    
    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(AllImagesData);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');
    const NavigationRef=React.useRef({});

    const zoomView=useRef(null);
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let imageType=params.imageType || {};
        let isBeat=params.isBeat || false;
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);
        setImageType(imageType);
        
        let navData={
            'storeData':storeData1,
            'menu':menu1,
            'isAdhocScreen':isAdhoc,
            'isBeat':isBeat,
            'imageType':imageType}

        NavigationRef.current=navData
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName
        getData(storeData1,menu1,imageType);

        // let t={"Uploadxml":"<DATA><USER_DATA><STORE_ID>4521</STORE_ID><CREATED_BY>testpromo</CREATED_BY><VISIT_DATE>06/27/2022</VISIT_DATE><STATUS>U</STATUS></USER_DATA></DATA>"}

        // console.log(JSON.stringify(t));
        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
      
        return function cleanup() {
            AppStateSubscription.remove();
            return unsubscribe;
        };
    }, []);   

        

    const _handleAppStateChange = async (nextAppState) => {
        
        if(nextAppState =='background' && hasUnsavedChangesRef.current==true){
           let newData = {
               storeBGData:WindowDataRef.current,
               menuName:ScreenNameRef.current,
               StoreId1:StoreIdRef.current,
               NavData:NavigationRef.current,
               visiteDate:d2
           }
           let WindowsStr= JSON.stringify(newData)
           await set_item('storeData',WindowsStr); 

       }
     }

    // useEffect(() => {
    //     const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
    //     return unsubscribe;
    // }, [hasUnsavedChanges]);   
    
    // useEffect(() => {
    //     const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
    //     return unsubscribe;
    // }, [showCamera]); 

    // useEffect(() => {
    //     const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
    //     return unsubscribe;
    // }, [show_zoomImage]); 
    
    function  onBeforeRemove(e){
        
        if(showCameraRef.current==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else if(show_zoomImageRef.current==true){
            e.preventDefault();
            BgShow_zoomImage(false);
        }
        else{
            if (hasUnsavedChangesRef.current==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
                return;
            }  
        } 
    }

    function BgUnsavedChanges(val){
        hasUnsavedChangesRef.current=val
        setHasUnsavedChanges(val);
    }

    function BgShowCamera(val){
        showCameraRef.current=val
        setShowCamera(val);
    }

    function BgShow_zoomImage(val){
        show_zoomImageRef.current=val
        setShow_zoomImage(val);
    }





    function BgWindowData(val){
        WindowDataRef.current=val
        setAllImagesData(val);
    }
    
    function onRemoveScreen(e){     
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
              {
                text: ST.Cancel,
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: async () => {
                // setHasUnsavedChanges(false);
                BgUnsavedChanges(false)
                await clear_item('storeData')
                props.navigation.dispatch(e.data.action);} }
            ]
          );
    }
    

    async function getData(storeData1,menu1,imageType){        
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;

            let AllKPIFields=await getKPIFields(menu1);
            setKPIFields(AllKPIFields);
            // set switch camera flag as defined in mapping menu flag (if exists)
            let SwitchingCameraI=AllKPIFields.findIndex(i=>i.KPIFieldName=='SwitchingCamera');
            let SwitchingCameraObj=SwitchingCameraI>=0?AllKPIFields[SwitchingCameraI]:{};
            let SwitchingCamera=SwitchingCameraI>=0?SwitchingCameraObj['KPIFieldEnable']:true;
            setShowSwitchCamera(SwitchingCamera);


            let windData = await get_item('storeData');
            let isBgDataExists=false;
            if(windData!=null && windData!=''){
                let StoreJson = JSON.parse(windData)
                let { storeBGData,menuName,StoreId1,visiteDate }= StoreJson
                if(storeBGData.length>0 && menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                    isBgDataExists=true;
                    BgUnsavedChanges(true)
                    BgWindowData(storeBGData);
                }
            }

            await db.transaction(async function (txn) {  
            
                
                let q=`Select * From ${AppTables.STORE_IMAGES} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and IMAGE_TYPE_ID='${imageType.ImageTypeId}'`;
                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            setImgCount(ImgCount+1)
                            let data =txnres2.rows.item(i);
                            let imgPath='file://'+ImageFolderPath+menu1.ScreenName+"/"+data.IMAGE;
                            let obj={'ImageName':data.IMAGE,'ImagePath':imgPath,lat:data.LAT,lng:data.LNG};
                            arr.push(obj);
                            if(i==txnres2.rows.length-1){
                                if(!isBgDataExists){
                                    BgWindowData(arr)
                                }
                                setProcessing(false);
                            }                                
                        }
                    }
                    else{
                        setProcessing(false);
                    }
                },function (txnE,txnerr) { console.log(txnerr);  setProcessing(false);},);
            });          
        } catch (err) {
          console.log(err);          
        }        
    }

    async function getPosition_global(successCallback){
       Geolocation.getCurrentPosition(
          async (position) => {
            let latitude=position.coords.latitude;
            let longitude=position.coords.longitude;
            latitude=parseFloat(parseFloat(latitude).toFixed(8).replace("-e",""));
            longitude=parseFloat(parseFloat(longitude).toFixed(8).replace("-e",""));

            let loc={lat:latitude,lng:longitude};
              
            console.log("location------",loc)
            successCallback(loc);  
          },
          (error) => {
              notify(ST.Cannotgetuserposition);
          },
          { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
        );

      }
  

    async function getImage(imgdata,Imglocation){
        let imageTypeName=ImageType.ImageType;
        let imageTypeId=ImageType.ImageTypeId;
        if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
            notify(ST.Cameraunavailable);
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();
            
            let picture_clicked_time=moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name=moment(picture_clickedd).format('MMDDYYYY_HHmmss')

            console.log("time", picture_clicked_time);
      console.log("time1", picture_clicked_time_for_pic_name);
      let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
      let calculate_tym_date_over_img = picture_clicked_time;

            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName+' - '+imageTypeName+' | Date:'+calculate_tym_date_over_img;
            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_'+imageTypeId+'Img-'+calculate_tym_date_for_filename+'.jpg';
            
            let allData=AllImagesData;
            let imgData={}
            let image_key='ImageName';
            let image_path_key='ImagePath';
            imgData[image_key]=filename;

            imgData['lat']=Imglocation.lat||0;
            imgData['lng']=Imglocation.lng||0;
        
            
            let imagePath='file://'+ImageFolderPath+currentMenu.ScreenName+"/"+filename;
            // if(resize_res.success){
                // file resized now rename file
                RNFS.copyFile(imgurl, imagePath)
                .then(async(resn) => {
                    let uri=imagePath;
                    console.log('image marker',uri);
                    imgData[image_path_key]=uri; 
                    allData.push(imgData);
                    setImgCount(ImgCount+1)

                    // setAllImagesData(allData);
                    // setHasUnsavedChanges(true);
                    BgWindowData(allData);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);


                    // add metdata then resize image and restored back to the imagePath
                    let restore_data={"destFilePath":imagePath,"imgurl":imgurl,imgWidth,imgHeight,mark_text1,mark_text2}
                    let is_restored=await restore_ImageWithMetaData(restore_data,imgdata);
                    console.log("image restored:",is_restored);
                })
                .catch(err => {
                    console.log('ERROR: image file write failed!!!');
                    console.log(err.message, err.code);
                }); 
        }        
    }

    async function getImageLocation(imgdata){
    await getPosition_global((res)=>getImage(imgdata,res))
    }
    async function openCamera(){  
        BgShowCamera(true);
    }

    async function removeImage(){
        let index=toRemoveIndex;
        let allData=AllImagesData;
        let imgData=allData[index];
        let imgPath=imgData.ImagePath || '';
        if(imgPath!=''){
            let imgPath1='file://'+imgPath;
            RNFS.unlink(imgPath1);
            if(ImgCount>0){
                setImgCount(ImgCount-1)
            }
        }
        allData.splice(index,1);
        // setAllImagesData(allData);
        BgWindowData(allData)
        setShowRemoveAlert(false);
        setrerenderdata(!rerenderdata);
    }

    async function  onRemoveImage(imgName,index){
        setToRemoveIndex(index);
        setShowRemoveAlert(true);
    }

    async function submit(){
        let isvalid=await validate();
        if(isvalid){
            Keyboard.dismiss();
           setShowAlert(true);
        }
    }

    async function validate(){
        let isValid=true;
        let {MaxImage}=ImageType;
        console.log('ImageType.MinImage:',ImgCount,"<",ImageType.MinImage,ImgCount<ImageType.MinImage,AllImagesData.length);
        if(AllImagesData.length<=0){
            isValid=false;
            notify('Please add images.');
        }else if(AllImagesData.length<ImageType.MinImage){
            isValid=false;
            notify(`Please add minimum ${ImageType.MinImage} images.`);
        }
        else if(MaxImage!=null && AllImagesData.length>MaxImage){
            isValid=false;
            notify(`You can add maximum of ${MaxImage} Images.`);
        }
        return isValid;
    }


    async function saveData(){
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
            let imgType=ImageType.ImageType;
            let imgTypeId=ImageType.ImageTypeId;

            await db.transaction(async function (txn) {   

                let q=`DELETE FROM ${AppTables.STORE_IMAGES} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and IMAGE_TYPE_ID='${ImageType.ImageTypeId}' `;
                //  remove old data
               
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    console.log('Images data deleted');
                    let values='';
                    if(AllImagesData.length>0){

                    
                    for(var i=0;i<AllImagesData.length;i++){
                        let imgData=AllImagesData[i];
                        let img=imgData.ImageName || '';
                        let lat=imgData.lat || 0;
                        let lng=imgData.lng || 0;

                        values+=values!=''?' , ':'';
                        values+=` ('${StoreId}','${d2}','${imgTypeId}','${imgType}','${img}','${lat}','${lng}','${d2}') `;
                    }

                    let add_HdrData=`INSERT INTO ${AppTables.STORE_IMAGES} (STORE_ID,VISIT_DATE,IMAGE_TYPE_ID,IMAGE_TYPE,IMAGE,LAT,LNG,ADDED_DATE) VALUES ${values} `;
                    await txn.executeSql(add_HdrData,[],async function (txn2, txnres) { 
                        console.log('Images added');
                        notify(ST.Imagesaddedsuccessfully);
                        setImgCount(0)
                        setProcessing(false);
                        props.navigation.goBack();
                    },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddimages) },);
                    }
                    else{
                        setImgCount(0)
                        notify(ST.Imagesaddedsuccessfully);
                        setProcessing(false);
                        props.navigation.goBack();
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);

              
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }

    function onSaveCancel(){
        setShowAlert(false);
    }

    function onRemoveCancel(){
        setShowRemoveAlert(false);
    }


    async function sendEmail(){
        console.log('uploadIMage');
        var message='<html><body><h3>This is Esha </h3></body></html>';
    
        await fetch(`http://192.168.2.127:8101/api/email`, {
            method: 'post',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                To:'eshakhare32@gmail.com',
                CC:'',
                Subject:'Test mail',
                HTMLContent:message,
            }),
        })
        .then((response)=>{
          console.log('response',response);
          if(response.status === 404) {}else { return response.json()}
    
        }).then((response)=>{
            console.log(response);
    
        }).catch((error)=>{
            console.log('error:',error);
        })
    
    
    }

    async function showImage(item,index){
        let ImagePath=item.ImagePath;
        let imgObj={imgIndex:1,url: ImagePath, props: {}}
        let arr=[imgObj];
        setZoomImageUrl(arr);     
        BgShow_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={()=>{BgShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#fff'} size={24}/>
                </TouchableOpacity>            
            </View> 
        )
    }

    function _renderTopEl(){
        let isMaxCountAvlbl=ImageType!=null && ImageType.MaxImage!=null && ImageType.MaxImage!='';
        let CamDisabled=isMaxCountAvlbl && AllImagesData.length>=ImageType.MaxImage ;
        return (
            <View>
                {
                    isMaxCountAvlbl && 
                    <View  style={customStyle.stImage_RedAlert}>
                        <Text style={customStyle.stImage_RedAlertTxt}>{`You can capture maximum ${ImageType.MaxImage} images.`}</Text>
                    </View>

                }
                <View style={customStyle.ImageCapCamWrap}>
                    <View style={customStyle.ImageCapCamCon}>
                        <TouchableOpacity disabled={CamDisabled} style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin,{backgroundColor:PageTheme.$secondary_color_dark,borderRadius:13,paddingHorizontal:6,paddingVertical:4,},(CamDisabled?{backgroundColor:PageTheme.$text_color_light2}:{})]} onPress={()=>{openCamera()}}>
                            <CameraImg width={50} height={50}  />                                     
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )
    }
   
  
    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}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {ConfirmSaveAlert(props,showRemoveAlert,onRemoveCancel,removeImage,ST.DoyoureallywanttoremovethisImage)}
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData)=>{BgShowCamera(false);getImageLocation(imgData)}} showCamera={showCamera} onHideCamera={()=>{BgShowCamera(false);}}/>   
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper,customStyle.zIndex0]}>
          <View style={[customStyle.pageContentWrapper,customStyle.ImgCapWrap]}>
            <View style={customStyle.ImageTypesLHd}>
                <Text  style={customStyle.ImageTypesLHdText}>{(ImageType.ImageType!=null?`${ST.Add} ${ImageType.ImageType}`:'')}</Text>
            </View>
            {/* <View style={{alignItems:'center'}}>
            <GradientButton {...props} title={'Send Email'} onPress={()=>{sendEmail()}}/> 
            </View> */}
            {_renderTopEl()}
            
            <View style={customStyle.ImageCapViewWrap}>
            {AllImagesData.length>0 &&
                AllImagesData.map((item,index)=>{
                    let ImagePath=item.ImagePath;
                    let ImageName=item.ImageName;
                    if(ImagePath!=null && ImagePath!=''){
                        return (
                            <View style={[customStyle.ImageCapImgViewOuter,(index%3==0?customStyle.ImageCapImgView1:(index%3==1?customStyle.ImageCapImgView2:customStyle.ImageCapImgView3))]} key={index}>
                            <TouchableOpacity activeOpacity={0.7} style={[customStyle.ImageCapImgView]} onPress={()=>{showImage(item,index)}}>
                                <Image style={customStyle.ImageCapImg} source={{uri:ImagePath}}/>
                                <TouchableOpacity style={[customStyle.ImageCapImgRemove]} onPress={()=>{onRemoveImage(ImageName,index)}}>
                                    <Ionicons name='trash' size={19} color={PageTheme.$accent_color}/>                                   
                                </TouchableOpacity>
                            </TouchableOpacity> 
                            </View> 
                        )
                    }
                    else{
                        return null
                    }
                    
                })
            }
            </View>
          
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{submit()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
       {show_zoomImage && 
        <View style={customStyle.album_ZOOM_wrap}>
            <ImageViewer ref={zoomView} style={[customStyle.album_ZOOM]} imageUrls={zoomImageUrl} 
            renderHeader={_renderHeader} renderIndicator={()=>null} 
            />
        </View>        
        }  
      </Container>   
    ); 
}

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