import React,{useState,useEffect, memo} 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} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, AppVersion, common_ImagePath} 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 Geolocation from '@react-native-community/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 cameraImg from '../assets/performics/camera_front_image.svg'
import CustomCamera from '../components/Camera';
import GradientButton from '../components/gradientButton';
import { CustomPicker } from '../components/CustomPicker';


function Attendance(props) { 
    const route = useRoute();
    
    const ST=props.StaticText || {};
    const AttendanceCons=[{"AttendanceId":1,"AttendanceName":"Holiday"},{"AttendanceId":2,"AttendanceName":"Leave"},{"AttendanceId":3,"AttendanceName":"Present"},{"AttendanceId":4,"AttendanceName":"Meeting"}]

    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    const [loaderTitle, setLoaderTitle] = useState();
    const [processing, setProcessing] = useState((props.isDataDownloaded?true:false));
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [nodataFound, setNodataFound] = useState(false);
    const [rerenderdata, setrerenderdata]= useState(false);
    const [EmployeesList, setEmployeesList] = useState([]);
    const [globalEmplist, setGlobalEmplist] = useState([]);
    const [globalStorelist, setGlobalStorelist] = useState([]);
    const [searchedItem, setSearchedItem]= useState('');
    const [showAlert, setShowAlert] = useState(false);
    const [dataFound, setdataFound] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [CameraVis, setCameraVis] = useState(false);
    const [showReason, setShowReason] = useState(false);
    const [showRemark, setShowRemark] = useState(false);
    const [AttData, setAttData] = useState({});
    const [getImageProps,setGetImageProps]= useState({});
    const [AttendanceLabels, setAttendanceLabels] = useState(AttendanceCons);
    const [nonWorkingRsns, setNonWorkingRsns] = useState([{"ReasonId":"1","Reason":"Reason 1"},{"ReasonId":"2","Reason":"Reason 2"},{"ReasonId":"3","Reason":"Reason 3"}]);
    
    useEffect(() => { 
      setLoaderTitle(ST.Loading+'...');
      checkLocalData();
      
      const onremoveSubscription=props.navigation.addListener('beforeRemove', onBeforeRemove);
      return function cleanup() {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
     };
    }, []);

    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [showCamera]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else{
            return;
        } 
    }

  
    async function checkLocalData(){
       
      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);
      
      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 obj={STATUS:STATUS,STATUS_Id:STATUS_Id,REMARK:REMARK,REASON_ID:REASON_ID, REASON:REASON,IMAGE1:IMAGE1};
            let path=IMAGE1!=null && IMAGE1!='' ? 'file://'+common_ImagePath+IMAGE1:''; 
            obj['IMAGE1_PATH']=path;
            

            if(STATUS_Id==2){
                setShowRemark(true);
                setShowReason(true);
                setCameraVis(false);
            }
            else if(STATUS_Id==3){
                setShowRemark(true);
                setShowReason(false);
                setCameraVis(true);
            }
            else{
                setShowRemark(false);
                setShowReason(false);
                setCameraVis(false);
            }

            setAttData(obj);
            setdataFound(true);
            setProcessing(false);
            setrerenderdata(!rerenderdata);
                    
          }
          else{            
            setProcessing(false); 
          }
        },function(txn2,txnerr){console.log(txnerr); setProcessing(false);});
      });      
    }

    
    async function onSelectAttendance(item){
       
        let alldata=AttData;
        alldata['STATUS']=item.AttendanceName;
        alldata['STATUS_Id']=item.AttendanceId;
        console.log('alldata',alldata);
        if(item.AttendanceId==2){
            setShowRemark(true);
            setShowReason(true);
            setCameraVis(false);
        }
        else if(item.AttendanceId==3){
            setShowRemark(true);
            setShowReason(false);
            setCameraVis(true);
        }
        else{
            setShowRemark(false);
            setShowReason(false);
            setCameraVis(false);
        }

        setAttData(alldata);
        setrerenderdata(!rerenderdata);

    }

    function onselectionChange(option,keyLbl,keyVal){
        let data=AttData;
        data[keyVal]=option.value;
        data[keyLbl]=option.label;
        setAttData(data);
        setrerenderdata(!rerenderdata)
    }

    function onchangeText(val,key){
        console.log('onchangeText',key);
        let data=AttData;
        data[key]=val;
        setAttData(data);
        setrerenderdata(!rerenderdata)

    }

    async function getImage(imgdata){
        // let type=getImageProps.type || '';
        if(typeof imgdata =='object' && imgdata.errorCode=='camera_unavailable'){
            notify('Camera unavailable');
        }
        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';
                            
                           
                            let data=AttData;
                            let image_key='IMAGE1';
                            let image_path_key='IMAGE1_PATH';
                            data[image_key]=filename;
                            
                            // renamefile
                            let imagePath=`${common_ImagePath}${filename}`;
                            RNFS.copyFile(res.uri, imagePath)
                            .then(resn => {
                                let uri='file://'+imagePath;
                                console.log('image marker',uri);
                                data[image_path_key]=uri; 

                                setAttData(data);
                                setrerenderdata(!rerenderdata);
                            })
                            .catch(err => {
                                console.log('ERROR: image file write failed!!!');
                                console.log(err.message, err.code);
                            });                           
                                     
                        }
                        else{
                            if(res.imagenotfound){
                                notify('Please capture a image');
                            }
                            else{
                                notify(res.error);
                            }
                        }
                    });
                }
                else{
                    if(res.imagenotfound){
                        notify('Please capture a image');
                    }
                    else{
                        notify(res.error);
                    }
                }
            });            
        }        
    }

    async function openCamera(){  
        setShowCamera(true);
    }


    async function onSubmitData(){
        let isvalid=await validate();
        if(isvalid){
           setShowAlert(true);
        }
    }

    function onSaveCancel(){
        setShowAlert(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 {STATUS,STATUS_Id,REMARK,REASON_ID, REASON,IMAGE1,IMAGE1_PATH}=AttData;
              values+=` ('${props.UserId}','${d2}','${STATUS}','${STATUS_Id}','${REMARK}','${REASON_ID}','${REASON}','${IMAGE1}','${d2}') `;
                    
              console.log('values:',values);
              let add_data=`INSERT INTO ${AppTables.ATTENDANCE} (EMP_ID,ATTENDANCE_DATE,STATUS,STATUS_Id,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');
                props.setAttendanceStatus({isAttendanceMarked:true});
                setdataFound(true);
                setProcessing(false);
                props.navigation.goBack();
              },function (txn2, txnerr) { console.log(txnerr);setProcessing(false);notify('Cannot submit Attendance!') },);
              
              
            });          
        } catch (err) {
            console.log(err);          
        } 
    }


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

        let d1=new Date();
        let d2=moment(d1).format('MM/DD/YYYY');    
        let {ATTENDANCE_DATE,STATUS,STATUS_Id,REMARK,REASON_ID, REASON,IMAGE1,IMAGE1_PATH}=AttData;
        
        var data1 = new FormData();          
        data1.append('file', {
          uri:  IMAGE1_PATH,
          type: 'image/jpg',
          name: IMAGE1,
        });
  
        data1.append('Foldername',"Attendance");
        data1.append('Path', d2);
        let data={
            "UserId":props.UserId,  
            "AttendanceDate":d2,
            "ReasonId":REASON_ID!=null?REASON_ID:0, 
            "ImageUrl":IMAGE1,  
            "Remark":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();

            // 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 validate(){
        let isValid=true;
        let {ATTENDANCE_DATE,STATUS,STATUS_Id,REMARK,REASON_ID, REASON,IMAGE1,IMAGE1_PATH}=AttData;
        if(STATUS_Id==null || STATUS_Id==''){
            isValid=false;
            notify('Please select Attendance Status','SHORT');
        }
        else if(showReason==true && (REASON_ID==null || REASON_ID=='')){
            isValid=false;
            notify('Please select reason','SHORT');
        }
        else if(showRemark==true && (REMARK==null || REMARK=='')){
            isValid=false;
            notify('Please enter remark','SHORT');
        }
        else if(CameraVis==true && (IMAGE1==null || IMAGE1=='')){
            isValid=false;
            notify('Please click image','SHORT');
        }

        console.log('isValid:',isValid);
        return isValid;
    }

    
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} title={(isAdhocScreen==true?'Adhoc Team List':'Team List')} />
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,uploadAttndance)}
        <CustomCamera cameraType={'front'} 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}>
          <View style={customStyle.pageContentWrapper}>
          { !props.isDataDownloaded && <NoDataComponent {...props}/>}
          
          { props.isDataDownloaded==true && 
            <View style={customStyle.attend_PageWrap}>
                <ScrollView
                    contentContainerStyle={customStyle.attend_scrollViewInner}
                    style={customStyle.attend_scrollView}
                >
                    {rerenderdata==rerenderdata && 
                    <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>
                        {
                        AttendanceLabels.map((item,index)=>{
                            let isSelected=AttData["STATUS_Id"]==item.AttendanceId;
                            return (
                                <TouchableOpacity style={[customStyle.selAttBtn,isSelected?customStyle.selAttBtn_selected:{}]} activeOpacity={dataFound?1:0.5} onPress={()=>{dataFound?'' :onSelectAttendance(item)}}>
                                    <Text style={[customStyle.selAttBtnText,isSelected?customStyle.selAttBtnText_selected:{}]}>{item.AttendanceName}</Text>
                                </TouchableOpacity>
                            )
                        })
                        }
                        {
                        <View style={customStyle.attend_extraDetails}>
                            {showRemark==true && 
                            <View style={[customStyle.addVisRow]}>
                                <View style={[customStyle.addVisCol100]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>Remark</Text>
                                        {dataFound && <Text style={[customStyle.addVisInputStyle,{padding:10}]}>{AttData['REMARK']}</Text>}
                                        {!dataFound && <TextInput  
                                        style={customStyle.addVisInputStyle} 
                                        value={(AttData['REMARK']!=null? AttData['REMARK']:'')}
                                        onChangeText={(val)=>{onchangeText(val,'REMARK');}}
                                        autoComplete='off'
                                        />}
                                    </View>
                                </View>
                            </View>}

                            {showReason==true && 
                            <View style={[customStyle.addVisRow]}>
                                <View style={[customStyle.addVisCol100]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>Reason</Text>
                                        {CustomPicker(props,nonWorkingRsns,'Reason','ReasonId','REASON','REASON_ID',onselectionChange,{value:AttData["REASON"]})}
                                    </View>
                                </View>
                            </View>}
                            {CameraVis==true && 
                            <View style={[customStyle.addVisRow]}>
                                <View style={[customStyle.addVisCol100]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>Image</Text>
                                        <View style={customStyle.addVisCameras}>
                                            <View style={customStyle.openStkCameraCon}>
                                                { (AttData["IMAGE1_PATH"]==null || AttData["IMAGE1_PATH"]=='') && 
                                                    <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin]} onPress={()=>{openCamera()}}>
                                                        <SvgXml width={80} height={80} xml={cameraImg}/>                                     
                                                    </TouchableOpacity>
                                                }
                                                { (AttData["IMAGE1_PATH"]!=null && AttData["IMAGE1_PATH"]!='') && 
                                                    <View style={customStyle.osCatImageView}>
                                                        <Image style={customStyle.osCatImage} source={{uri:AttData["IMAGE1_PATH"]}}/>
                                                        {!dataFound && <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera()}}>
                                                            <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                        </TouchableOpacity>}
                                                    </View>                                    
                                                }       
                                            </View>
                                            
                                        </View>
                                    </View>
                                </View>
                            </View>}
                        </View>
                        
                        }

                        <View>

                        </View>
                    </View>}
                </ScrollView>
                {
                    !dataFound && 
                    <View style={[customStyle.opening_Stock_btnWrap]}>
                    <GradientButton {...props} title={'Submit'} onPress={()=>{onSubmitData()}}/> 
                    </View> 
                }
            </View>
          }
          
         </View>      
       </LinearGradient>       
       
      </Container>   
    ); 
  }
  


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