import React,{useState,useEffect} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles,GetPageTheme } from "../styles/Global";
import {Image,View,Text,ScrollView,TouchableOpacity,FlatList} from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {marktext1,marktext2, UpdateStoreStatus, UploadData, UploadData2, UploadFormData} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {AppVersion, common_ImagePath, db, URL_IMAGE, version} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign, Entypo, 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 CustomModal from '../components/CustomModal';
import GradientButton from '../components/gradientButton';
import {launchCamera, launchImageLibrary,CameraOptions} from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import {_checkLocationPermission} from '../components/geolocation';
import CustomCamera from '../components/Camera';

import cameraImg from '../assets/performics/camera_front_image.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { AppTables } from '../constants/tableConstants';
import { uploadStoreStatus } from '../constants/uploadData';
import { ConfirmSaveAlert } from '../components/alert';


function Attendance(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((props.isDataDownloaded?true:false));
    
    
    const [nonWorkingRsns, setNonWorkingRsns] = useState([]);
    const [selectedReason, setSelectedReason] = useState({});
    const [reason, setReason] = useState('');
    const [reasonId, setReasonId] = useState('');
    const [Image1, setImage1] = useState('');
    const [Image1Path, setImage1Path] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [rerenderdata, setrerenderdata]= useState(0);
    const [location, setLocation] = useState({});
    const [loaderTitle, setLoaderTitle] = useState();
    const [showAlert, setShowAlert] = useState(false);
     
    
    const [isAnyStoreUploaded, setIsAnyStoreUploaded] = useState(false);

    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
   

    useEffect(() => { 
      setLoaderTitle(ST.Loading+'...')
      getdata();
      

      const onremoveSubscription=props.navigation.addListener('beforeRemove', onBeforeRemove);

      return function cleanup() {
        onremoveSubscription();
      };
    }, []);

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

    function  onBeforeRemove(e){
      if(showCamera==true){
          e.preventDefault();
          setShowCamera(false);
      }
      else{
        return;
      } 
    }


    async function getdata(){
        let d1=new Date();
        let d2=moment(d1).format('MM/DD/YYYY');
  
        let token=await get_item('loginToken');
        let loginInfo=await get_item('loginInfo');
        const loginDetails=JSON.parse(loginInfo);
        let nonWrkRsns=await getNonWorkingRsns() || [];

        if(nonWrkRsns.length>0){
              
            await db.transaction(async function (txn) {   
                let q=`select * from ${AppTables.ATTENDANCE} where ATTENDANCE_DATE='${d2}' and EMP_ID='${props.UserId}'`;
                await txn.executeSql(q,[],async function (txn2, txnres2) {  
                if(txnres2.rows.length>0){ 
                    let data=txnres2.rows.item(0); 
                    let {ATTENDANCE_DATE,STATUS,STATUS_Id,REMARK,REASON_ID, REASON,IMAGE1}=data
                    let path=IMAGE1!=null && IMAGE1!='' ? 'file://'+common_ImagePath+IMAGE1:''; 
                    let selRsn=nonWrkRsns.find(i=>i.ReasonId==REASON_ID);
                    setSelectedReason(selRsn);
                    setReason(REASON);
                    setReasonId(REASON_ID);
                    setImage1Path(path);
                    setImage1(IMAGE1);
                    
                    setProcessing(false);
                    setrerenderdata(!rerenderdata);
                }
                else{   
                    
                    setProcessing(false); 
                }
                },function(txn2,txnerr){console.log(txnerr); setProcessing(false);});
            });  
        }
        else{
            setProcessing(false);
        }

    }

    async function getNonWorkingRsns(){
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');
      let token=await get_item('loginToken');
      let loginInfo=await get_item('loginInfo');
      const loginDetails=JSON.parse(loginInfo);

      let nonWrkRsns=[];
      
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {  
                let q=`SELECT * FROM Sup_NonWorkingReason where ShowAttendance='1'`;
        
                await txn.executeSql(q,[],async function (txn2, txnres2) {     
                    console.log('data len:',txnres2.rows.length);      
                  if(txnres2.rows.length>0){ 
                    // show from local
                    
                    for(var i=0;i<txnres2.rows.length;i++){
                      let sdata=txnres2.rows.item(i);               
                      nonWrkRsns.push(sdata); 
                      if(i==(txnres2.rows.length-1)){
                        console.log(nonWrkRsns);
                        setNonWorkingRsns(nonWrkRsns);
                        resolve(nonWrkRsns);
                      }
                    }            
                  }
                  else{            
                    resolve(nonWrkRsns);
                    notify(ST.Nodatafound);
                  }
                },function(txn2,txnerr){console.log(txnerr);resolve(nonWrkRsns);});
            });
        }).catch((err)=>{
            console.log(err);
            return nonWrkRsns;
        })
      
    }

    async function onSubmitData(){
        if(validate()){
        //   setLoaderTitle(ST.UploadingData+'...');
          setShowAlert(true);        
        }      
    }

    function validate(){
        if(reasonId=='' || reasonId==null || reason=='' || reason==null){
          notify("Please select reason",'SHORT');
          return false;
        }
        if(( selectedReason.ImageAllow=='true' || selectedReason.ImageAllow=='1') && (Image1Path=='' || Image1Path==null)){
          notify("Please click selfie",'SHORT');
          return false;
        }
        return true;
    }

    
    async function uploadAttndance(){
        setShowAlert(false);
        setLoaderTitle('Uploading Data...');
        setProcessing(true);

        let d1=new Date();
        let d2=moment(d1).format('MM/DD/YYYY');    
        let {ImageAllow}=selectedReason;
        
        var data1 = new FormData();          
        data1.append('file', {
          uri:  Image1Path,
          type: 'image/jpg',
          name: Image1,
        });
  
        data1.append('Foldername',"Attendance");
        data1.append('Path', d2);
        let data={
            "UserId":props.UserId,  
            "AttendanceDate":d2,
            "ReasonId":reasonId!=null && reasonId!=''?reasonId:0, 
            "ImageUrl":((ImageAllow=='1' || ImageAllow=='true')?Image1:''),  
            "Remark":"",
        }
  
        
  
        const url=props.baseurl+getMethodName(METHODS.UPLOADATTENDANCE_METHOD);
        const url1=(props.imageUploadUrl || URL_IMAGE)+getMethodName(METHODS.UPLOADIMAGES_METHOD);
        console.log(url,data);
        
        await UploadData2(url,data)
        .then(async(res)=>{         
          console.log('res upload attend:',res);
          if(parseInt(res)>0){
            saveData();
            if(selectedReason.ImageAllow=='1' || selectedReason.ImageAllow=='true' || selectedReason.ImageAllow==1)
            {
                // Upload Image 
                await UploadFormData(url1,data1)
                .then(async(res1)=>{         
                console.log('res1 image upload:',res1);            
                })
                .catch((err)=>{
                console.log(err);
                }); 
            }
          }
          else{
            setProcessing(false);
          }
        })
        .catch((err)=>{
          console.log(err);setProcessing(false);
        });
    }

    async function saveData(){
        
        const d1=new Date();
        const d2=moment(d1).format('MM/DD/YYYY');
        try {   
          
            await db.transaction(async function (txn) {   

              let q=`DELETE FROM ${AppTables.ATTENDANCE} WHERE EMP_ID='${props.UserId}' and ATTENDANCE_DATE='${d2}' `;
              
              //  remove old data
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('attend deleted');
              },function (txn2, txnerr) { console.log(txnerr); },);

              var values='';
              let {EntryAllow}=selectedReason;
              values+=` ('${props.UserId}','${d2}','${EntryAllow}','','${reasonId}','${reason}','${Image1}','${d2}') `;
                    
              console.log('values:',values);
              let add_data=`INSERT INTO ${AppTables.ATTENDANCE} (EMP_ID,ATTENDANCE_DATE,ENTRY_ALLOW,REMARK,REASON_ID, REASON,IMAGE1 ,ADDED_DATE) VALUES ${values} `;

              await txn.executeSql(add_data,[],async function (txn2, txnres) { 
                console.log('attend added');
                notify('Attendance submited successfully','SHORT');
                setProcessing(false);
                props.setAttendanceStatus({isAttendanceMarked:true,isEntryAllow:(EntryAllow=='1' || EntryAllow=='true'?true:false)});
                props.navigation.goBack();
              },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot submit Attendance!') },);
              
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }
    

    async function selectReason(item){
      

      setSelectedReason(item);
      setReason(item.Reason);
      setReasonId(item.ReasonId);
      setrerenderdata(!rerenderdata);
      
      if(item.ImageAllow=='1' || item.ImageAllow=='true'){
        if((Image1Path!='' && Image1Path!=null)){
          setShowImageSaveOp(false);
        }
        else{
          setShowImageSaveOp(true);
        }
        openImageModal();
      }
    }

    function onSaveCancel(){
        setShowAlert(false);
    }

    function openImageModal(){
      setShowModal(true);    
    }

    function closeImageModal(){
      setShowModal(false);
    }

    function cancelImage(){
      setImage1('');
      setImage1Path('');
      closeImageModal();
    }

    async function getImage(imgdata){
      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.height;
         
          
          let picture_clicked_time=new Date();
          picture_clicked_time=moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')
          
          
          const mark_text1=picture_clicked_time;
          const mark_text2='User Id:'+props.UserId+' | Image Type: Attendance'+' | Date:'+picture_clicked_time;
           
          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=(props.UserId || '')+'_AttendanceImg-'+picture_clicked_date+'_'+picture_clicked_time+'.jpg';
                            
                          setImage1(filename);
                          // renamefile
                          let imagePath=`${common_ImagePath}${filename}`;
                          RNFS.copyFile(res.uri, imagePath)
                          .then(resn => {
                              let uri='file://'+imagePath;
                              console.log('image marker',uri);
                              setImage1Path(uri);  
                          })
                          .catch(err => {
                              console.log(ST.Errorimagefilewritefailed+'!!!');
                              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);
      setShowModal(false)
      // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'front'})
    }
  
    function _OpenCaptureImage_Modal(){
      const isImageCap=(Image1Path=='' || Image1Path==null)?false:true;
      return (
        <CustomModal 
          style={customStyle.nonWCapImgModal}
          title={"Mark Attendance"}
          message={"Please click the selfie for attendance"}
          titleStyle={customStyle.nonWCapImgModal_title}
          messageStyle={customStyle.nonWCapImgModal_subtitle}
          showModal={showModal}
        >
          {
            !isImageCap && 
            <View style={customStyle.nonWCapImgModalCon}>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Camera} onPress={()=>{openCamera()}}>
                <SvgXml width={100} height={100} xml={CameraImg2}/>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{closeImageModal()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
              </TouchableOpacity>
            </View>
          }
          { 
          isImageCap && 
          <View style={customStyle.nonWCapImgModalCon}>
            <View style={customStyle.nonWCapImgModal_ImgWrap}>
              <Image  style={[customStyle.nonWCapImgModal_Img,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:Image1Path}} />
            </View>
            <TouchableOpacity style={customStyle.nonWCapImgModal_CameraSmall} onPress={()=>{openCamera()}}>
              <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color}/>
            </TouchableOpacity>
            { showImageSaveOp &&
            <View style={customStyle.nonWCapImgModal_btng}>              
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{cancelImage()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.nonWCapImgModal_Save_btn} onPress={()=>{closeImageModal()}}>
                <Text style={customStyle.nonWCapImgModal_Save_btnText}>{ST.Save}</Text>
              </TouchableOpacity>
            </View>}
            {!showImageSaveOp &&
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={()=>{closeImageModal()}}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Close}</Text>
              </TouchableOpacity>
            }
            
          </View>

          }
        </CustomModal>
      )
    }

  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        
        <CustomHeader {...props} title={'Attendance'}/>        
        {showModal && _OpenCaptureImage_Modal()}
        {showAlert && ConfirmSaveAlert(props,showAlert,onSaveCancel,uploadAttndance)}
        <CustomCamera cameraType={'front'} onImageCaptured={(imgData)=>{setShowCamera(false);setShowModal(true);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,customStyle.pageContentWrapper_bgLight]}>
          { !props.isDataDownloaded && <NoDataComponent {...props}/>}
          {props.isDataDownloaded &&
            <View style={customStyle.attenContent}>
                <View style={customStyle.attend_infoCon}>
                    <Text style={customStyle.attend_infoText1}>Hi User</Text>
                    <Text style={customStyle.attend_infoText2}>Please mark attendance before working!</Text>
                </View>
                <View style={customStyle.nonWorking_con}>
                    <View style={customStyle.nonWorking_form}>                       
                    <FlatList 
                    contentContainerStyle={customStyle.attendList_scroll}
                    extraData={rerenderdata}
                    style={[(props.isAttendanceMarked==true?customStyle.attendList_scrollCon2:customStyle.attendList_scrollCon)]}
                    data={nonWorkingRsns}
                    renderItem={({item,index})=>{

                        const nWselStyle=reasonId==item.ReasonId?customStyle.selAttBtn_selected:{};
                        const nWselStyleText=reasonId==item.ReasonId?customStyle.nWselStyleText:{};
                        const CapImageShow=(Image1Path!='' && Image1Path!=null) && reasonId==item.ReasonId?true:false;
                        let isDisabled=props.isAttendanceMarked==true && reasonId!=item.ReasonId;


                        return (
                        <TouchableOpacity key={index} style={[customStyle.nonWlist,nWselStyle,isDisabled==true?{backgroundColor:'#cdcdcd'}:{}]} disabled={isDisabled} activeOpacity={props.isAttendanceMarked==true?1:0.5} onPress={()=>{props.isAttendanceMarked==true ?'':selectReason(item)}}>
                            <Text style={[customStyle.nonWlist_Text,nWselStyleText]}>{item.Reason}</Text>
                            { (item.ImageAllow=='1' || item.ImageAllow=='true') && 
                            <TouchableOpacity  style={customStyle.nonWlist_camera} disabled={isDisabled} onPress={()=>{selectReason(item)}}>
                                {!CapImageShow && <SvgXml width={30} height={30} xml={CameraImg2} />}
                                {CapImageShow && <SvgXml width={30} height={30} xml={CameraImg3} />}
                            </TouchableOpacity>
                            }
                        </TouchableOpacity>
                        );
                    }}
                    />
                    </View>                
                </View>
              
              {props.isAttendanceMarked==false && 
              <View style={customStyle.nonW_btnWrap}>
                <GradientButton {...props} title={"Submit"} onPress={()=>{onSubmitData();}}/> 
              </View>  }  

            </View>   
            
          }          
         </View>      
       </LinearGradient>       
        
      </Container>   
    ); 
  }
  



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