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 } 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 { 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, validateNumber } from '../controller/functions';
import { ConfirmSaveAlert } from '../components/alert';
import GradientButton from '../components/gradientButton';
import { AppTables } from '../constants/tableConstants';
import { METHODS, getMethodName } from '../constants/methodNames';
import { FlatList } from 'react-native';
import { getImagePOSTData } from '../constants/uploadData';
import CustomModal from '../components/CustomModal';



function GateMeeting(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 [showCamera, setShowCamera] = useState(false);
    const [formData, setFormData] = useState({});
    const [rerenderdata, setrerenderdata] = useState(0);

    const [processing, setProcessing] = useState(false);
    const [gateMeeting,setgateMeeting] = useState([]);
    const [discussionPoints,setdiscussionPoints] = useState([]);

    const [EmployeeName,setEmployeeName] = useState([]);

    const [EmployeeID,setEmployeeID] = useState([]);
    const [image, setimage] = useState({});
    const [getImageProps,setGetImageProps]= useState({});
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    const [showRemoveConfirm_M,setshowRemoveConfirm_M]= useState(false);  
    const [toRemoveId,setToRemoveId]= useState('');
    const [showRAllC_M,setShowRAllC_M]= useState(false);
    const [toRemoveItem,setToRemoveItem]= useState({});
    const [AddVisibility, setAddVisibility] = useState([]);
    const [showAlert, setShowAlert] = useState(false);
    const [loaderTitle, setLoaderTitle] = useState('loading...');

    const [selectedItems, setSelectedItems] = useState([]);
    const d1=new Date();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [nodataFound, setNodataFound] = useState(false);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [currentCheckOutItem, setCurrentCheckOutItem]= useState({});
    const [removedVisitor, setRemovedVisitor]= useState({});
    
    const [showCheckOutModal, setShowCheckOutModal]= useState(false);
    const [showRemoveVistor, setShowRemoveVistor]= useState(false);
    const [DErrorMsg, setDErrorMsg] = useState({});
  
    const [showDErrAlert, setshowDErrAlert] = useState(false);

    const d2=moment(d1).format('MM/DD/YYYY');
    const time = moment(d1).format('hh:mm:ss');
    
    // const DATA = [
    //   { id: EmployeeID, name: MerchandiserName },
    // ];
  
    useEffect(() => {
      
      // getData();

      const willFocusSubscription = props.navigation.addListener('focus', () => {
        
        getData();
      });

      return willFocusSubscription;
    }, [ ]);
    

    async function getData(){
      setLoaderTitle(ST.Loading+'...');
      setProcessing(true);
       
      try{
        db.transaction(async function (txn) {   
          // get inserted audit
          let q = `SELECT * FROM ${AppTables.GATE_MEETING} `
          db.transaction(async function (txn) {   
            txn.executeSql(q,[],async function (txn2, txnres2) {  
              if(txnres2.rows.length>0){ 
                // show from local
                let gatemeeting=[];
                for(var i=0;i<txnres2.rows.length;i++){
                  let data=txnres2.rows.item(i); 
                  let dpoints=await getDiscussionPoint(data) ;
                  dpoints=dpoints!=null?dpoints:[];
                  data["DISCUSSION_POINTS"] = dpoints
                  gatemeeting.push(data)
                  if(i==(txnres2.rows.length-1))
                  {
                    setgateMeeting(gatemeeting);
                    setProcessing(false);
                    setrerenderdata(!rerenderdata);
                  }
                }            
              }
              else{
                setProcessing(false); notify(ST.Nodatafound);setNodataFound(true);
              }
            },function(txn2,txnerr){console.log(txnerr); setProcessing(false); notify(ST.Nodatafound);setNodataFound(true);});
          });      
        });  
      }
      catch(err){
        console.log(err);
      }
    }

  async function getDiscussionPoint(gateMeeting){

    return new Promise((resolve,reject)=>{
      db.transaction(async function (txn) {   
        // get inserted audit
        let q = `SELECT DISCUSSION_POINTS FROM ${AppTables.GATE_MEETING_DISCUSSION} WHERE GATEMEETING_ID='${gateMeeting.UNIQUE_ID}'  `
        await db.transaction(async function (txn) {   
          await txn.executeSql(q,[],async function (txn2, txnres2) {    
            // console.log('txnres4',txnres2.rows.length)
            if(txnres2.rows.length>0){ 
              // show from local
              let dp=[];
              for(var i=0;i<txnres2.rows.length;i++){
                let data=txnres2.rows.item(i); 
                console.log('data---->',data)
                dp.push(data.DISCUSSION_POINTS)
                
                if(i==(txnres2.rows.length-1))
                {
                  setdiscussionPoints(dp)
                  setrerenderdata(!rerenderdata);
                  resolve(dp)
                }
              }            
            }
            else{
              setrerenderdata(!rerenderdata);
              resolve([])

            }

          },function(txn2,txnerr){console.log(txnerr);resolve([]) });
        }); 
            
      });    
    }).then((val)=>{
      return val;
    }).catch((err)=>{
      return []
    });
  } 


    function showRemoveGateMeetPopUp(data,index){
      setToRemoveItem(data);
      setToRemoveId(index);
      setshowRemoveConfirm_M(true);
    }

    function Remove_DP(){
      let index=toRemoveId;
      let data=toRemoveItem;
      setLoaderTitle("Remove Gate Meeting..")
      setProcessing(true);
      setshowRemoveConfirm_M(false);
      try{
        let {UNIQUE_ID}=data;
        db.transaction(async function (txn) {   
          // delete data from gate meetting table
          let q = `Delete from ${AppTables.GATE_MEETING} WHERE UNIQUE_ID='${UNIQUE_ID}'  `
          await txn.executeSql(q,[],async function (txn2, txnres2) {    
            console.log("Removed data from Gate Meeting");

            // remove data from discussion points
            let q2 = `Delete from ${AppTables.GATE_MEETING_DISCUSSION} WHERE GATEMEETING_ID='${UNIQUE_ID}'  `
            await txn.executeSql(q2,[],async function (txn2, txnres2) {    
              console.log("Removed data from Gate Meeting discussion points");
              let alldata=gateMeeting;
              alldata.splice(index,1);
              setgateMeeting(alldata);
              notify("Removed Successfully!")
              setProcessing(false);
            },function(txn2,txnerr){console.log(txnerr);setProcessing(false); notify("Cannot remove data!")});
          },function(txn2,txnerr){console.log(txnerr); setProcessing(false); notify("Cannot remove data!")});

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

    async function uploadGateMeetingData(data,index){
      const url=props.baseurl+getMethodName(METHODS.UPLOADJSON_METHOD);
      setLoaderTitle("Uploading Data...")
      setProcessing(true);
      console.log('gmuploaddata',typeof(data.EMP_ID))
      let empIDs =data.EMP_ID!=null && data.EMP_ID!='' && data.EMP_ID!=undefined ?data.EMP_ID+'':[];
      let employeesArr=empIDs!=null&&empIDs!=''? empIDs.split(',') :[];

      let obj={
        "MID":0,
        "UniqueId":data.UNIQUE_ID,
        "UserId":props.UserId,
        "VisitDate":d2,
        "Time":data.TIME,
        "Image":data.IMAGE,
        "MerchandiserId":employeesArr,
        "DiscussionPoints":data.DISCUSSION_POINTS
      }
    
      let JsonChange=JSON.stringify(obj)?.replace(/'/g, '"')
    
      let postData={
        "MID":0,
        "Keys":"GateMeeting_Sup",
        "JsonData":JsonChange,
        "UserId":props.UserId,
      };
    
      console.log('postData',postData)
    
      let ImageName = data.IMAGE;
      let imgPath='file://'+`${common_ImagePath}${ImageName}`;
      
      await UploadData2(url,postData)
      .then(async(res)=>{
        console.log('res:',res);
        if(res.UploadJsonResult!=null && res.UploadJsonResult=='Success'){
          
    
          // uplod images
          const url2=(props.imageUploadUrl || URL_IMAGE)+getMethodName (METHODS.UPLOADIMAGES_METHOD);
          let upload_status = 'U';
          if(ImageName!='' && ImageName!=null){
            let file={
              uri: imgPath,
              type: 'image/jpeg',
              name: ImageName,
              filetype:'image',
              folderName:'SupGateMeetingImages',
            }
    
            let isExists=await RNFS.exists(file.uri).then((res)=>{return res;});
            console.log('isExists file',isExists);
            if(isExists==true){
              let fileData=getImagePOSTData(file,d2);
            
              let isImageUploaded=await UploadFormData(url2,fileData);
              console.log('isImageUploaded',isImageUploaded)
              if(isImageUploaded.success==false){
                let obj={"ErrorMsg":"!! Network Connection Failed..! Please Connect Internet!!!"}
               
                upload_status='D'
                notify('Cannot upload image!');
              }
            }
            else{
              notify("Error uploading image! Image does not exists");
            }
          }
    
          let isupdated =updateGateMeetUploadStatus(data.UNIQUE_ID,upload_status);
          if(isupdated){
            notify('Data Uploaded Sucessfully!');
            setProcessing(false);
            //update status locally
            data.UPLOADSTATUS="U";
            let alldata=gateMeeting;
            // let GMIndex=alldata.findIndex(i=>i.UNIQUE_ID==data.UNIQUE_ID);
            if(index>=0){
              alldata[index]=data;
              setgateMeeting(alldata);
              setrerenderdata(!rerenderdata)
            }
          }
          else{
            setProcessing(false);
            notify("Cannot update upload status!");
          }
          
        }else{
          setProcessing(false);
          notify(ST.Cannotuploaddata);
        }
      })
      .catch((err)=>{
          console.log(err);
          setProcessing(false);
          notify(ST.Cannotuploaddata);
      }); 
    
    }
    async function uploadImageOnly(data,index){
      const url=props.baseurl+getMethodName(METHODS.UPLOADJSON_METHOD);
      setLoaderTitle("Uploading Image...")
      setProcessing(true);
      
      let ImageName = data.IMAGE;
      let imgPath='file://'+`${common_ImagePath}${ImageName}`;
      const url2=(props.imageUploadUrl)+getMethodName (METHODS.UPLOADIMAGES_METHOD);
          
      let upload_status='U';
      if(ImageName!='' && ImageName!=null){
        let file={
          uri: imgPath,
          type: 'image/jpeg',
          name: ImageName,
          filetype:'image',
          folderName:'SupGateMeetingImages',
        }

        let isExists=await RNFS.exists(file.uri).then((res)=>{return res;});
        console.log('isExists file',isExists);
        if(isExists==true){
          let fileData=getImagePOSTData(file,d2);
        
          let isImageUploaded=await UploadFormData(url2,fileData);
          console.log('isImageUploaded',isImageUploaded)
          if(isImageUploaded.success==false){
            upload_status='D'
            notify('Cannot upload image!');
          }
        }
        else{
          notify("Image does not exists!");
        }
      }

      let isupdated =updateGateMeetUploadStatus(data.UNIQUE_ID,upload_status);
      if(isupdated){
        notify('Data Uploaded Sucessfully!');
        setProcessing(false);
        //update status locally
        data.UPLOADSTATUS="U";
        let alldata=gateMeeting;
        // let GMIndex=alldata.findIndex(i=>i.UNIQUE_ID==data.UNIQUE_ID);
        if(index>=0){
          alldata[index]=data;
          setgateMeeting(alldata);
          setrerenderdata(!rerenderdata)
        }
      }
      else{
        setProcessing(false);
        notify("Cannot update upload status!");
      }
    
    }
    async function updateGateMeetUploadStatus(uniqueId,upload_status){
      return new Promise((resolve,reject)=>{
        db.transaction(async function (txn) { 
          let q=`Update ${AppTables.GATE_MEETING} SET UPLOADSTATUS='${upload_status}' WHERE USER_ID='${props.UserId}' AND VISIT_DATE='${d2}' and UNIQUE_ID='${uniqueId}'`;
          await txn.executeSql(q,[],async function (txn2, txnres) { 
            console.log('Gate Meeting upload status Updated');
            resolve(true);
          },function (txn2, txnerr) { console.log(txnerr);resolve(false); },);
        });   
      }).then((val)=>{
        return val;
      }).catch((err)=>{
        console.log(err);
        return false;
      });
    }


    return ( 
      
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        
        <CustomHeader {...props} title={'GateMeeting'} hideBellIcon={false} hideTimer={false}/> 
        {/* {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)} */}
       
        {ConfirmSaveAlert(props,showRemoveConfirm_M,()=>{setshowRemoveConfirm_M(false)},Remove_DP,'Do you really want to remove this Discussion Points?')}
        

        <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.gmeet_header]}>
              <Text style={customStyle.vl_visitorsListText}>{'Gate Meeting Status'}</Text>
              <TouchableOpacity style = {[customStyle.hr_viewButton]} onPress={()=>{
                props?.navigation?.navigate('AddGateMeeting')
                }}>
                <Text style = {[customStyle.hr_viewButtonText]}>Add</Text>
              </TouchableOpacity>
            </View>
          
            { rerenderdata==rerenderdata &&
            <ScrollView 
              contentContainerStyle={customStyle.gmeet_scroll} 
              style={customStyle.gmeet_scrollOuter}
              showsVerticalScrollIndicator={false}
              >
              {gateMeeting.map((item,index)=>{
                  let data = item||'';
                  // console.log("data.MERCHANDISER_NAME:",data)
                  let MeetDate=data.VISIT_DATE!=null  && data.VISIT_DATE!='' ?data.VISIT_DATE:"";
                  let MeetDT=data.TIME!=null && data.TIME!=''?MeetDate+" "+data.TIME:MeetDate;
                   let time2 = MeetDT ? moment(MeetDT, MeetDT.includes('/')
                                                ? "MM/DD/YYYY HH:mm:ss"
                                                : "HH:mm:ss"
                                             ).format("HH:mm:ss")
                                             : '';

                  //let formattedDT=MeetDT!=""?moment(MeetDT).format("DD/MM/YYYY h:mm:ss"):"";
                  return(
                    <View style={customStyle.gm_TblHeader}>
                      {data.UPLOADSTATUS!='U'  &&
                      <TouchableOpacity style={customStyle.gm_DeleteBtn} onPress={()=>{showRemoveGateMeetPopUp(item,index)}}>
                        <Ionicons name='trash' color={PageTheme.$red} size={24} />
                      </TouchableOpacity>
                      }
                      <View style={[customStyle.gm_TblHeaderBox1]}>
                        <Text style={customStyle.vl_TblHeaderTxt}>{'Date & Time :'}</Text>
                        <Text style={customStyle.gm_TblHeaderTxt}>{time2}</Text>
                      </View>
                      <View style={[customStyle.gm_TblHeaderBox2]}>
                        <Text style={customStyle.vl_TblHeaderTxt}>{'Merchandisers/Promoters :'}</Text>
                        <Text style={customStyle.gm_TblHeaderTxt2}>{data.MERCHANDISER_NAME}</Text>
                      </View>
                      <View style={[,customStyle.gm_TblHeaderBox3]}>
                        <Text style={customStyle.vl_TblHeaderTxt}>{'Discussion Point :'}</Text>
                        {
                          data.DISCUSSION_POINTS.map((item,index)=>{
                            return(
                              <Text style={customStyle.gm_TblHeaderTxt3}>{item}</Text>
                            )
                          })
                        }
                      </View>
                      {data.UPLOADSTATUS!='U'  && 
                      <View style={[customStyle.vl_visitorsLI_Box,customStyle.vl_visitorsLI_Box3]}>
                        <TouchableOpacity style={customStyle.gm_CheckOutBtn} onPress={()=>{data.UPLOADSTATUS=='D'?uploadImageOnly(item,index) :uploadGateMeetingData(item,index)}}>
                          <Text style={customStyle.vl_CheckOutBtnText}>{'Upload'}</Text>
                        </TouchableOpacity>
                      </View>
                      }

                      {data.UPLOADSTATUS=='U' && 
                      <View style={[customStyle.vlStatus]}>
                        <Ionicons name='checkmark-done-sharp' color='green' size={20}/>
                        <Text style={[customStyle.storel_usText,{color:'green'}]}>{ST.Uploaded}</Text>
                      </View>
                      }

                      {data.UPLOADSTATUS=='D' &&
                      <View style={[customStyle.vlStatus]}>
                        <Ionicons name='checkmark-sharp' color='red' size={20}/>
                        <Text style={[customStyle.storel_usText,{color:'red'}]}>{"Data Uploaded, Image Pending!"}</Text>
                      </View>
                      }

                      {(data.UPLOADSTATUS=='' || data.UPLOADSTATUS==null || data.UPLOADSTATUS==undefined) && 
                      <View style={[customStyle.vlStatus]}>
                        <Ionicons name='checkmark-sharp' color='red' size={20}/>
                        <Text style={[customStyle.storel_usText,{color:'red'}]}>{"Data Pending, Image Pending!"}</Text>
                      </View>
                      }
                    </View>

                  )
                
              })}
            </ScrollView>
            }
         </View>
        </LinearGradient>

      </Container>   
    ); 
  }


  
  
  

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