import React,{useState,useEffect} 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,SafeAreaView} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import moment from 'moment';
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import cameraImg from '../assets/performics/camera_front_image.svg'

import CustomHeader from '../components/customHeader';
import Svg, { SvgUri, SvgXml} from 'react-native-svg';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import * as RNFS from 'react-native-fs';
import MultiSelect from 'react-native-multiple-select';
import {notify} from '../components/notify';
import {get_item} from '../components/localStorage';
import { URL_IMAGE, common_ImagePath, db, resumeurl} from '../constants/constants';
import { PrimaryTheme } from '../styles/Themes';
import CustomCamera from '../components/Camera';
import { FontAwesome, Ionicons, MaterialCommunityIcons } from '../components/icons';
import { UploadData2, UploadFormData, getDownloadJson, getDownloadJson1, validateNumber } from '../controller/functions';
import { ConfirmSaveAlert } from '../components/alert';
import GradientButton from '../components/gradientButton';
import { AppTables } from '../constants/tableConstants';
import { getDevice } from 'react-native-device-info';
import { UploadImagesWithoutWait, getImagePOSTData } from '../constants/uploadData';
import { METHODS, getMethodName } from '../constants/methodNames';
import CustomModal from '../components/CustomModal';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import { Item } from 'react-native-paper/lib/typescript/src/components/List/List';
import NoDataComponent from '../components/NoDataComponent';
import DownloadDataModal from '../components/downloadDataModal';



function AttendanceSup(props) { 
    const route = useRoute();
    // console.log('props',props)
    const ST=props.StaticText || {};
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    const [processing, setProcessing] = useState(false);
    
    const [loaderTitle, setLoaderTitle] = useState('loading...');
    const [showCamera, setShowCamera] = useState(false);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [attData,setattData] = useState([]);
    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    const [empAttData, setempAttData] = useState([]);
    const [nwData, setnwData] = useState({});
    const [dataattendance, setdataattendance] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [nodataFound, setnodataFound] = useState(false);
    const [isAnyPending, setisAnyPending] = useState(false);
    const [serverTime, setServerTime] = useState("");

    const [uploadedCount, setUploadedCount] = useState(0);
    const [TotalUpCount, setTotalUpCount] = useState(0);
    const [startUploading, setStartUploading] = useState(false);
    const [UploadingSubText, setUploadingSubText] = useState("");
    const [UploadingText, setUploadingText] = useState("Uploading Data...");
    const [showProgresssBar, setshowProgresssBar] = useState(false);
    
 

  

 
    useEffect(() => {
      setLoaderTitle(ST.Loading+'...')
      let params=props.route.params? props.route.params:{};
      
      getData();
      
      const willFocusSubscription = props.navigation.addListener('focus', () => {
        
    });

    return willFocusSubscription;
  }, [ ]);  


  async function getData(){
    setLoaderTitle(ST.Loading+'...');
    setProcessing(true);

    let isDataDownloaded=await downloadData();
    console.log('isDataDownloaded:',isDataDownloaded);
    try{
      db.transaction(async function (txn) {   

        let q2=`SELECT ReasonId,Reason FROM Sup_NonWorkingReason where ShowAttendance='1'`;
      
        await txn.executeSql(q2,[],async function (txn2, txnres2) {     
            console.log('data len:',txnres2.rows.length);    
            let arr=[];  
            if(txnres2.rows.length>0){ 
              // show from local
              
              for(var i=0;i<txnres2.rows.length;i++){
                let data=txnres2.rows.item(i);  
                arr.push(data);
                if(i==(txnres2.rows.length-1)){
                  setnwData(arr);
                }
              }            
            }
        },function(txn2,txnerr){console.log(txnerr);});


        // get inserted audit
        let join =`Left Outer Join ${AppTables.ATTENDANCE_DATA} a on a.EMP_ID=t.EmpId and a.VISIT_DATE=t.AttDate`;
        let q = `SELECT t.*,a.REASON_ID as ReasonId,a.REASON as Reason,a.UPLOADSTATUS as UploadStatus FROM Sup_TeamAttendance t ${join}`
        // q= `SELECT * FROM ${AppTables.ATTENDANCE_DATA}`;
        txn.executeSql(q,[],async function (txn2, txnres2) {  
          console.log('loaded data : ',txnres2.rows.length)
          if(txnres2.rows.length>0){ 
          
            let attendanceData=[],arr=[],isAnyPending1=false;
            for(var i=0;i<txnres2.rows.length;i++){
                let data=txnres2.rows.item(i); 
               
                attendanceData.push(data)
                let ReasonId=(data.ReasonId!=null && data.ReasonId!="undefined")?data.ReasonId:"";
                let Reason=(data.Reason!=null && data.Reason!="undefined")?data.Reason:"";
                let UploadStatus=(data.UploadStatus!=null && data.UploadStatus!="undefined")?data.UploadStatus:"";
                
                let dataobj={'EmpId':data.EmpId,"ReasonId":ReasonId,"Reason":Reason,"UploadStatus":UploadStatus}
                arr.push(dataobj)
                // data.SupEntryAllow=1;
                if(data.SupEntryAllow==1){
                  isAnyPending1=true;
                }
                if(i==0){
                  setServerTime(data.ServerTime);
                }

                if(i==(txnres2.rows.length-1))
                {
                  setattData(attendanceData);
                  setempAttData(arr);
                  setisAnyPending(isAnyPending1);
                  setProcessing(false);
                  setrerenderdata(!rerenderdata);
                }
            }            
          }
          else{
            setProcessing(false); notify(ST.Nodatafound);
          }
        },function(txn2,txnerr){console.log(txnerr); setProcessing(false); notify(ST.Nodatafound);});
       
        
        
        // let q3 = `SELECT * FROM ${AppTables.ATTENDANCE_DATA} `
        // db.transaction(async function (txn) {   
        //   txn.executeSql(q3,[],async function (txn2, txnres2) {  
        //     if(txnres2.rows.length>0){ 
        //       // show from local
        //       let attendanceData=[];
        //       for(var i=0;i<txnres2.rows.length;i++){
        //         let data=txnres2.rows.item(i); 
        //         attendanceData.push(data)
        //         if(i==(txnres2.rows.length-1))
        //         {
        //           setdataattendance(attendanceData);
        //           setProcessing(false);
        //           setrerenderdata(!rerenderdata);
        //         }
        //       }            
        //     }
        //     else{
        //       setProcessing(false); notify(ST.Nodatafound);
        //     }
        //   },function(txn2,txnerr){console.log(txnerr); setProcessing(false); notify(ST.Nodatafound);});
        // });  
      });  
    }
    catch(err){
      console.log(err);
    }
  }

  async function downloadData(){
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
  
    let url=props.baseurl+getMethodName(METHODS.DOWNLOADJSON_METHOD);
    let postdata={
      Downloadtype:"Sup_TeamAttendance",
      Username: loginDetails.UserId,
      Param1: '',
      Param2: '',
    };
    return await getDownloadJson1(url, postdata)
      .then(async(res) => {     
        let isAdded=await insertData(res);
        console.log("isAdded",isAdded);
        return isAdded; 
      })
      .catch(err => {
        console.log('onPage Team error', err);
        return false;
      });
  }

  async function insertData(res){
    
    return new Promise((resolve,reject)=>{
      if (res!=null && typeof res == 'object' && res.Sup_TeamAttendance!=null && res.Sup_TeamAttendance!='') {
        let data_arr = res.Sup_TeamAttendance || [];          
       
        var values=[];
        data_arr.map((data_obj)=>{  
          let {EmpId,AttDate,EmployeeName,Attendance,ServerTime,SupEntryAllow}=data_obj;
          values.push(` ('${EmpId}', '${AttDate}', '${EmployeeName}', '${Attendance}', '${ServerTime}', '${SupEntryAllow}')`);
        });
  
        var all_vals=values.join(',');
        var sql_stmnt=`INSERT INTO Sup_TeamAttendance(EmpId,AttDate,EmployeeName,Attendance,ServerTime,SupEntryAllow) 
        values ${all_vals}`;
        
        db.transaction(function(txn) {
          // delete all today data
          txn.executeSql(`delete from Sup_TeamAttendance where 1=1`,[],function(txn1,txnres){
              // insert or refresh all today data
              txn.executeSql(sql_stmnt,[],function(txn1,txnres){
                  console.log('Sup_TeamAttendance added');
                  resolve(true);
              },function(txn1,err){
                  console.log('err:',err);
                  notify("Cannot insert data!");
                  resolve(false);
              });                         
          },function(txn1,err){
            console.log('err:',err);
            notify("Cannot insert data!");
            resolve(false);
          });                                        
        });  
        
      }
      // pass to the next download key if data does not exists for this Key
      else if(res!=null && typeof(res)=='object' && (res[0]!=null && res[0].Result!=null && res[0].Result=="No Data")){
        console.log('No data found'); 
        notify("No data found!");
        setnodataFound(true);
        resolve(true);
      }
      // Stop Downloading and report error
      else if(res!=null && typeof(res)=='object' && res.success==false){
        notify("Error in downloaidng data! Network Issue"+JSON.stringify(res));
        resolve(false);
      }
      // Stop Downloading and report error
      else{ 
        notify("Error in downloaidng data!"+JSON.stringify(res)); 
        resolve(false);
      }
    }).then((val)=>{
      return val;
    }).catch((err)=>{ 
      console.log("err",err);
      notify("Error while adding data!")
      return false;
    })
    
   
  }


  function onselectionChange(option,keyLbl,keyVal,otherData){
    let item = otherData.EmpData
    let allData=empAttData;
    const win_index=allData.findIndex(i=>i.EmpId==item.EmpId);
    let wind=win_index>=0?(allData[win_index] || {}) :{};
    wind[keyVal]=option.value;
    wind[keyLbl]=option.label;
    win_index>=0?allData[win_index]=wind:allData.push(wind);
    setempAttData(allData);
    setrerenderdata(!rerenderdata);
    
}


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

async function saveData(){
  console.log()
  // setHasUnsavedChanges(false);
  setShowAlert(false);
  setLoaderTitle('Saving Data...');
  setProcessing(true);
  

  try {   
  
      await db.transaction(async function (txn) {  
        
        // delete old data 
        let q=`DELETE FROM ${AppTables.ATTENDANCE_DATA} WHERE VISIT_DATE='${d2}' `;
        
        await txn.executeSql(q,[],async function (txn2, txnres) { 
          console.log('prev att data removed');
        },function (txn2, txnerr){ console.log(txnerr);});


        let values='';  
        let dataToUpload=[];
        for(var i=0;i<attData.length;i++){
          let data=attData[i];
          if(data.SupEntryAllow==1 || data.UploadStatus=='U' ){
            let allData=empAttData;
            let windIndex= allData.findIndex(i=>i.EmpId==data.EmpId)
            let empData=windIndex>=0?empAttData[windIndex]:{};
            let ReasonId=empData.ReasonId!=null && empData.ReasonId!=''?empData.ReasonId:'0';
            let UploadStatus=data.UploadStatus=='U'?"U":"P";

            values +=values!=''?' , ':'';
            values +=` ('${d2}','${props.UserId}','${data.EmpId}','${ReasonId}','${empData.Reason ||''}','${UploadStatus}','${d2}') `;
            
            if(data.SupEntryAllow==1 && data.UploadStatus!='U'){
              let obj={"EmpId":data.EmpId,"ReasonId":ReasonId}
              dataToUpload.push(obj);
            }

            
            data["UploadStatus"]=UploadStatus;
            attData[i]=data;
            if(i==attData.length-1){
              setattData(attData);
              setrerenderdata(!rerenderdata);
            }
          }
        }

        if(dataToUpload.length>0){
          let add_data=`INSERT INTO ${AppTables.ATTENDANCE_DATA} (VISIT_DATE,USER_ID,EMP_ID,REASON_ID,REASON,UPLOADSTATUS,ADDED_DATE) VALUES ${values} `;
          console.log('add_data:',add_data);
          await txn.executeSql(add_data,[],async function (txn2, txnres) { 
            console.log('att data added');
            notify('Attendance added successfully!','SHORT');
            uploadAttendanceData(dataToUpload);
          },function (txn2, txnerr){ console.log(txnerr);notify('Cannot add attendance data') });
        }
        else{
          setProcessing(false);
          notify("All data already uploaded!");
        }
          
        
      });          
  } catch (err) {
      console.log(err);          
  } 
}

async function uploadAttendanceData(dataToUpload){
  setStartUploading(true);
  setProcessing(false);
  setshowProgresssBar(true);
  setTotalUpCount(dataToUpload.length-1);
  let uploadC=0;
  const url=props.baseurl+getMethodName(METHODS.UPLOADTAJSON_METHOD);
  
  Promise.all(
    dataToUpload.map(async(item,index)=>{
      let postData={
        "EmpId" : item.EmpId,
        "UserId": props.UserId,
        "AttendanceDate": d2,
        "ReasonId": item.ReasonId
      } 
      console.log('postData',postData,url)
      setUploadingSubText("Uploading data for EmpId:"+item.EmpId);
      await UploadData2(url,postData)
      .then(async(res)=>{
        console.log('res:',res);
        if(res==1){
          let isupdated=await updateAttDataUploadStatus(item.EmpId);
          console.log('isupdated',isupdated)
          if(isupdated){
            uploadC++;
            setUploadedCount(uploadC-1);
            return true
          }
          else{
            return false
          }
          
        }else{
          return false
        }
      })
      .catch((err)=>{
          console.log(err);
          return false
      }); 
    })
  ).then((res)=>{
    notify("Cannot upload all data! Please retry")
    setStartUploading(false);
  }).catch((err)=>{
    console.log('error',err);
    notify("Cannot upload data!")
    setStartUploading(false);
  })

  

}


async function updateAttDataUploadStatus(empId){
  console.log("updateAttDataUploadStatus called empId:",empId)
  return new Promise((resolve,reject)=>{
    db.transaction(async function (txn) { 
      let q=`Update ${AppTables.ATTENDANCE_DATA} SET UPLOADSTATUS='U' WHERE USER_ID='${props.UserId}' AND VISIT_DATE='${d2}' and EMP_ID='${empId}'`;
      await txn.executeSql(q,[],async function (txn2, txnres) { 
        console.log('Attendance Data upload status Updated');
        updateLocalStatus('U',empId);
        resolve(true);
      },function (txn2, txnerr) { console.log(txnerr);resolve(false); },);
    });   
  }).then((val)=>{
    return val;
  }).catch((err)=>{
    console.log(err);
    return false;
  });
}

function updateLocalStatus(status='',empId){
  let allAtt=attData;
  let empDIndex=allAtt.findIndex(i=>i.EmpId==empId);
  let empD=empDIndex>=0?allAtt[empDIndex]:{};
  empD["UploadStatus"]="U";
  empDIndex>=0?allAtt[empDIndex]=empD:'';
  setattData(allAtt);
  setrerenderdata(!rerenderdata);
}


function onSaveCancel(){
    setShowAlert(false);
}



async function validate(){
  let isValid=true;
  attData.map((item,index)=>{
    if(isValid){
      console.log("item in validate:",item)
      let empDataI= empAttData.findIndex(i=>i.EmpId==item.EmpId)
      let empData =empDataI>=0?empAttData[empDataI]:{}
      
      if(item.UploadStatus!="U" && item.SupEntryAllow==1 && (empData.ReasonId=='' || empData.ReasonId==null)){
        notify('Please select reason for attendance');
        isValid=false;
      }
    }
  })
  
  return isValid;
}

function render_attList(){
  // let now=moment();
  // let end=moment(new Date(d2+" "+serverTime));
  // let timeDiff=now.diff(end);
  // console.log("timeDiff:",timeDiff,now.format("HH:mm:ss"), serverTime,moment.duration(timeDiff).asHours());
  return (
    <ScrollView 
    contentContainerStyle={customStyle.gmeet_scroll} 
    style={customStyle.gmeet_scrollOuter}
    showsVerticalScrollIndicator={false}
    >
      <View style={customStyle.attsup_TblBody}>
      {
        attData.length>0 &&
        attData.map((item,index)=>{

      
          let empDataI= empAttData.findIndex(i=>i.EmpId==item.EmpId)
          let empData =empDataI>=0?empAttData[empDataI]:{}
      
          return(
            <View style={[customStyle.vl_visitorsLItem,((index<(attData.length-1))?customStyle.vl_visitorsLItemB:{})]} key={index}>
              <View style={[customStyle.vl_visitorsLI_Box,customStyle.attsup_Box1]}>
                <Text style={customStyle.attsup_Txt}>{item.EmpId}</Text>
              </View>
              <View style={[customStyle.vl_visitorsLI_Box,customStyle.attsup_Box2]}>
                <Text style={customStyle.attsup_Txt}>{item.EmployeeName}</Text>
              </View>
              
              {item.SupEntryAllow==0 &&
              <View style={[customStyle.attsup_Box3]}>
                <Text style={customStyle.attsup_Txt}>{item.Attendance}</Text>
                <View style ={customStyle.attsup_vtext}>
                  { item.UploadStatus!=null && item.UploadStatus!='' && item.UploadStatus=='U'  &&
                  <View style={customStyle.attsup_statusCon}>
                    <Ionicons name='checkmark-done-sharp' color='green' size={20}/>
                    <Text style={customStyle.attsup_utext}>{'Uploaded'}</Text>
                  </View>
                  }
                  { item.UploadStatus!=null && item.UploadStatus!='' && item.UploadStatus!='U'  &&
                  <View style={customStyle.attsup_statusCon}>
                    <Text style={customStyle.attsup_ntext}>{'Pending'}</Text>
                  </View>
                  }
                </View>
              </View>
              }
              {item.SupEntryAllow==1 && 
              <View style={customStyle.attsup_dl}> 
                {CustomPicker(props,nwData,'Reason','ReasonId','Reason','ReasonId',onselectionChange,{value:empData.Reason,otherData:{"EmpData":empData}})}
                <View style ={customStyle.attsup_vtext}>
                  { item.UploadStatus!=null && item.UploadStatus!='' && item.UploadStatus=='U'  &&
                  <View style={customStyle.attsup_statusCon}>
                    <Ionicons name='checkmark-done-sharp' color='green' size={20}/>
                    <Text style={customStyle.attsup_utext}>{'Uploaded'}</Text>
                  </View>
                  }
                  { item.UploadStatus!=null && item.UploadStatus!='' && item.UploadStatus!='U'  &&
                  <View style={customStyle.attsup_statusCon}>
                    <Text style={customStyle.attsup_ntext}>{'Pending'}</Text>
                  </View>
                  }
                </View>
              </View>
              }
              
            </View>
          )
        })
      }
      </View>
    </ScrollView>
  )
}
  // console.log('nonWorkingRsns',nonWorkingRsns)
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        {(startUploading) && <DownloadDataModal title={UploadingText} downloadCount={uploadedCount} totalCount={TotalUpCount} subtitle={UploadingSubText} showProgresssBar={showProgresssBar}/>}
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}

        <CustomHeader {...props} title={'Attendance List'}/>     
        {/* {_OpenCaptureImage_Modal()}   */}
        <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]}>
          <View style={customStyle.attsup_HText}>
              <Text style={customStyle.attsupdate_HText}>{'Date :'}</Text>
               <Text style = {[customStyle.attsupdate_Text]}>{d2}</Text>
          </View>
       
       
          <View  style={customStyle.attsup_View} ></View>

          <View>
              {/* <Text style={customStyle.vl_visitorsListText}>{ST.Visitors}</Text> */}
              <View style={customStyle.attsup_TblHeader}>
              <View style={[customStyle.attsup_HeaderBox,customStyle.attsup_HeaderBox1]}>
                  <Text style={customStyle.attsup_HeaderTxt}>{'Emp Id'}</Text>
              </View>
              <View style={[customStyle.attsup_HeaderBox,customStyle.attsup_HeaderBox2]}>
                  <Text style={customStyle.attsup_HeaderTxt}>{'Employee Name'}</Text>
              </View>
              <View style={[customStyle.attsup_HeaderBox,customStyle.attsup_HeaderBox3]}>
                  <Text style={customStyle.attsup_HeaderTxt}>{'Attendance'}</Text>
              </View>
         
              </View>
          </View>

          {nodataFound==true && <View style={customStyle.noDataCon}><Text style={customStyle.noDataText}>{"No data found"}</Text></View>}
          { nodataFound==false && rerenderdata==rerenderdata &&
            render_attList()
          }
          
          { isAnyPending==true && 
          <View style={[customStyle.opening_Stock_btnWrap]}>
            <GradientButton {...props} title={'Save'} onPress={()=>{onSubmitData()}}/> 
          </View>   
          } 
                 
         </View>
       
       </LinearGradient>       
        
      </Container>   
    ); 
  
  }
export default connect(mapStateToProps, mapDispatchToProps)(AttendanceSup);