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} 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,marktext1,marktext2, validateNumber} 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, 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 { 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 cameraImg from '../assets/performics/add_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { Q_getpaidvisibility } from '../constants/ConstantQueries';
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import { ConfirmSaveAlert, ExitScreenAlert } from '../components/alert';
import CustomCamera from '../components/Camera';
import ImageViewer from 'react-native-image-zoom-viewer';
import { getKPIFields } from '../controller/functions';

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 [getImageProps,setGetImageProps]= useState({});
    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [EmpData, setEmpData] = useState([]);
    const [MenuConfig, setMenuConfig] = useState([]);
    // const [KPIFields, setKPIFields] = useState([]);
    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 empData1=params.empData || {};
        
        let isAdhoc=params.isAdhoc || false;
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setEmpData(empData1);
        setCurrentMenu(menu1);
        setImageType(imageType);
        
        getData(storeData1,menu1,imageType);
        getKPIFieldsmenu(menu1);

       

        // 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));

        props.navigation.addListener('beforeRemove', onBeforeRemove);

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

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

    async function getKPIFieldsmenu(menu1){
       
        let menuconfig = await getKPIFields(menu1);
        setMenuConfig(menuconfig)
     console.log('menuconfig',menuconfig)
    }


    
    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){    
        {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);}  
        // Alert.alert(
        //     "",
        //     ST.Doyoureallywanttoexitthescreen,
        //     [
        //       {
        //         text: ST.Cancel,
        //         onPress: () => {},
        //         style: "cancel"
        //       },
        //       { text: ST.OK, onPress: () => {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);} }
        //     ]
        //   );
    }
    

    async function getData(storeData1,menu1,imageType){        
        try {   
          let {StoreId,ChainId,StateId,StoreTypeId,MerchandiserId}=storeData1;
         
          
          await db.transaction(async function (txn) {  
        
            
            let q=`Select * From ${AppTables.STORE_IMAGES} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' and VISIT_DATE='${d2}' and IMAGE_TYPE_ID='${imageType.ImageTypeId}'`;
            await txn.executeSql(q,[],async function (txn2, txnres2) { 
                console.log('dataq',q)
                console.log('txn2',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);
                        console.log('data',data)
                        let imgPath='file://'+common_ImagePath+data.IMAGE;
                        let obj={'ImageName':data.IMAGE,'ImagePath':imgPath, remark:data.REMARK};
                        
                        console.log('check value',obj,"---", data)
                        arr.push(obj);
                        if(i==txnres2.rows.length-1){
                           
                            setAllImagesData(arr);
                            setProcessing(false);
                        }                                
                    }
                }
                else{
                    setProcessing(false);
                }
            },function (txn2, txnerr) { console.log(txnerr); },);
          });          
        } catch (err) {
          console.log(err);          
        }        
    }

  
  

    async function getImage(imgdata){
        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='file://'+img.uri, imgWidth=img.width, imgHeight=img.height;
            let picture_clicked_time2=new Date();
            picture_clicked_time2=moment(picture_clicked_time2).format('DD-MM-YYYY HH:mm:ss')
            
            
            const mark_text1=picture_clicked_time2;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+imageTypeName+' | Date:'+picture_clicked_time2;
           
            await marktext1(mark_text1,imgurl)
            .then((res)=>{
                if(res.success){
                    let uri=res.uri;
                    marktext2(mark_text2,uri,imgWidth,imgHeight)
                    .then((res)=>{
                        if(res.success){
                            let picture_clickedd=new Date();
                            let picture_clicked_date=moment(picture_clickedd).format('YYYYMMDD');
                            let picture_clicked_time=moment(picture_clickedd).format('HHmmss');
                            let filename=storeData.StoreId+'_'+(props.UserId || '')+'_'+imageTypeId+'Img-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                           
                            // console.log('remarkdata',remarkdata)

                            
                            let allData=AllImagesData;
                            let imgData={}
                            let image_key='ImageName';
                            let image_path_key='ImagePath';
                            imgData[image_key]=filename;
                            
                            // renamefile
                            let imagePath='file://'+common_ImagePath+filename;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri=imagePath;
                                // imgData=remarkdata;
                                console.log('image marker',uri);
                                imgData[image_path_key]=uri; 
                                // imgData=remarkdata;
                                allData.push(imgData);
                                console.log('alldata',allData)
                                setAllImagesData(allData);
                                setHasUnsavedChanges(true);
                                setrerenderdata(!rerenderdata);
                            })
                            .catch(err => {
                                console.log('ERROR: image file write fail   ed!!!');
                                console.log(err.message, err.code);
                            });
                                          
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify(ST.Pleasecaptureaimage);
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify(ST.Pleasecaptureaimage);
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }
  
    async function openCamera(){  
        setShowCamera(true);
        // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
    }

    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);
        }
        allData.splice(index,1);
        setAllImagesData(allData);
        setShowRemoveAlert(false);
        setrerenderdata(!rerenderdata);
    }

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

    async function submit(){
        let isvalid=await validate();
        console.log('isvalid:',isvalid);
        if(isvalid){
           setShowAlert(true);
        }
    }

    async function validate()
    {
        var isValid=true;
        let isBRStockMandIndex=MenuConfig.findIndex(i=>i.KPIFieldName=='ShowRemark')
        let isBRStockMandKPIObj=isBRStockMandIndex>=0?MenuConfig[isBRStockMandIndex]:{};
        let isRemarkEnable=isBRStockMandIndex>=0?isBRStockMandKPIObj['KPIFieldEnable']:false;
        let isRemarkEnableMand=isBRStockMandIndex>=0?isBRStockMandKPIObj['KPIMandatory']:false;
    
        let isRemarkDisName=isRemarkEnable>=0?isBRStockMandKPIObj['KPIFieldDisplayName']:'';
       
        
    
        if(AllImagesData.length<=0){
            notify('Please click atleast one image!');
            console.log('error found');
            isValid=false;
        
         }
         else if(AllImagesData.length>0){
            for(var i=0;i<AllImagesData.length;i++){
            AllImagesData.map((item,index)=>{
             let Remark=item.remark;
             console.log('remarkvalid',Remark)
             console.log('Validate isRemarkEnableMand:',isRemarkEnable,isRemarkEnableMand,(Remark==null || Remark==undefined || Remark=='undefined' || Remark==''));
                if(isRemarkEnable && isRemarkEnableMand  && (Remark==null || Remark==undefined || Remark=='undefined' || Remark=='') ){
                notify('Please enter ' + isRemarkDisName+ '!');
                console.log('error found');
                isValid=false;
                }
         }
         
    )}
        }
   
        return isValid;
    }

    // function onFormDataChange(val,key,type=''){
       
    //     let data=AllImagesData;
    //     data[key]=val;
    //     setAllImagesData(data);
    //     setHasUnsavedChanges(true);
    //     setrerenderdata(!rerenderdata);
    // }

        
    function onTextChange(key, val,type='',index){
        console.log("onTextChange AllImagesData:",AllImagesData,index)
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }

        if(index!=null && index>=0) {
            let data=AllImagesData;
            console.log('',AllImagesData)
            let obj = data[index];
            obj[key]=val;
            data[index]=obj;
            console.log('onTextChangeData',data)
        
        
            setAllImagesData(data);
            setrerenderdata(!rerenderdata);
            setHasUnsavedChanges(true);
        }
        
        
    }


    async function saveData(){
        setHasUnsavedChanges(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 EMP_ID='${storeData.MerchandiserId}' 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];
                        console.log('saveImageData',imgData)
                        console.log('saveimgData',imgData)
                        let img=imgData.ImageName || '';
                        let remark=imgData.remark
                        values+=values!=''?' , ':'';
                        values+=` ('${storeData.MerchandiserId}','${StoreId}','${d2}','${imgTypeId}','${imgType}','${img}','${remark}','${d2}') `;
                        console.log('values add_HdrData:',values)
                    }
                   
                    let add_HdrData=`INSERT INTO ${AppTables.STORE_IMAGES} (EMP_ID,STORE_ID,VISIT_DATE,IMAGE_TYPE_ID,IMAGE_TYPE,IMAGE,REMARK,ADDED_DATE) VALUES ${values} `;
                    console.log('add_HdrData',add_HdrData)
                    console.log('txnres2',txnres)
                    await txn.executeSql(add_HdrData,[],async function (txn2, txnres) { 
                      
                        console.log('Images added');
                        notify(ST.Imagesaddedsuccessfully);
                        setProcessing(false);
                        props.navigation.goBack();
                    },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddimages) },);
                    }
                    else{
                        notify(ST.Imagesaddedsuccessfully);
                        setProcessing(false);
                        props.navigation.goBack();
                    }
                },function (txn2, 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);     
        setShow_zoomImage(true);
    }

    function _renderHeader(currentIndex){        
        return(
            <View style={[customStyle.album_ZOOM_topBar,{backgroundColor:'#000',overflow:'hidden'}]}>
                {/*,borderWidth:1,borderColor:'#fff',position:'absolute',top:0,zIndex:1  */}
                {/* <Text style={customStyle.album_ZOOM_indicator}>{`${(currentIndex+1)}/${zoomImageUrl.length}`}</Text> */}
                <TouchableOpacity style={[customStyle.album_ZOOM_backBtn]} onPress={()=>{setShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#fff'} size={24}/>
                </TouchableOpacity>            
            </View> 
        )
    }


    function _renderImages(){
        let isBRStockMandIndex=MenuConfig.findIndex(i=>i.KPIFieldName=='ShowRemark')
        console.log('isBRStockMandIndex',isBRStockMandIndex)
        let isBRStockMandKPIObj=isBRStockMandIndex>=0?MenuConfig[isBRStockMandIndex]:{};
        let isBRStockMandEnable=isBRStockMandIndex>=0?isBRStockMandKPIObj['KPIFieldEnable']:false;
        console.log('isBRStockMandEnable',isBRStockMandEnable)
        let ShowMBQLabelDisName=isBRStockMandEnable>=0?isBRStockMandKPIObj['KPIFieldDisplayName']:'';


        return(
            <View style={customStyle.ImageCapViewWrap}>
            {AllImagesData.length>0 &&
                AllImagesData.map((item,index)=>{
                    console.log('renderitem',item)
                    let ImagePath=item.ImagePath;
                    let ImageName=item.ImageName;
                    let Remark=item.remark;
                    console.log('remarkView',Remark)
                    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> 
                               {
                                isBRStockMandEnable == true &&
                                <View style = {[customStyle.Remarkdirection,{height:40}]}>
                                    {/* <Text style={customStyle.TextRemarkfont}>{ShowMBQLabelDisName}</Text> */}
                                    <TextInput 
                                        style={[customStyle.textRemark_Input,{height:40}]}
                                        placeholderTextColor={PageTheme.$placeholder_color} 
                                        value ={(Remark)}
                                        multiline={true}
                                        onChangeText={(val)=>{onTextChange('remark',val,'text',index)}}
                                        autoComplete='off'
                                    />
                                </View>
                                }
                            </View> 
                        )
                    }
                    else
                    {
                        return null
                    }
                    
                })
            }
            </View>
        )
    }
  
    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}`}/>        
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {ConfirmSaveAlert(props,showRemoveAlert,onRemoveCancel,removeImage,ST.DoyoureallywanttoremovethisImage)}
        <CustomCamera cameraType={'back'} enableCameraFlip={true} 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,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> */}
            
            <ScrollView
            contentContainerStyle={customStyle.hr_scroll} 
            style={customStyle.resume_scrollOuter}
            showsVerticalScrollIndicator={false}>
                <View style={customStyle.ImageCapCamWrap}>
           
                <View style={customStyle.ImageCapCamCon}>
                    <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin,{backgroundColor:PageTheme.$secondary_color_dark,borderRadius:13,paddingHorizontal:6,paddingVertical:4,}]} onPress={()=>{openCamera()}}>
                        <SvgXml width={50} height={50} xml={cameraImg} />                                     
                    </TouchableOpacity> 
                    </View>
                
                
            </View>
            {_renderImages()}
          
            </ScrollView>
            <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);