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 } 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 CameraImg2 from '../assets/performics/camera_icon.svg';
import CustomCamera from '../components/Camera';
import NoAttendance from '../components/NoAttendance';
import HeaderTabsTeam from '../components/HeaderTabsTeam';

const EmployeeItem = memo((props) => {
  const route = useRoute();
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const item = props.item;

  let params = props.route.params ? props.route.params : {};
  let isAdhoc = params.isAdhoc || false;

  console.log("params=====>",params)

  const ST = props.StaticText || {};

  let hasCheckedInEmployee = props?.list?.some(emp => emp.ChekedInStatus === true);
  // console.log("list============",props.list, hasCheckedInEmployee)


  // const gotoPage = React.useCallback(() => {
  //   // If no one else is checked in or this employee has an empty CheckInStatus, allow navigation

  //   const isCheckedIn = await checkStoreCheckIn(true, false, props);
  //   console.log("Checked In:", isCheckedIn);


  //   if (!hasCheckedInEmployee || item.ChekedInStatus === '') {
  //     props.navigation.navigate('StoreList', { empData: item, isAdhoc: false });

  //   } else if (item.ChekedInStatus === true) {
  //     // If the current employee is checked in, allow navigation
  //     props.navigation.navigate('StoreList', { empData: item, isAdhoc: false });
  //   } else {
  //     // Restrict navigation if someone else is checked in
  //     notify("You have some Checked In data for other employee.");
  //   }
  // }, [item, hasCheckedInEmployee, props.navigation]);

  //new React memo with async

  const gotoPage = React.useCallback(() => {
    const checkAndNavigate = async () => {
      try {
        const isCheckedIn = await checkStoreCheckIn(item, props);
        console.log("Checked In:", isCheckedIn);

        console.log('item===>',item);
        

        if (isCheckedIn.length == 0) {
          if (!hasCheckedInEmployee || item.ChekedInStatus === '') {
            props.navigation.navigate('StoreList', { empData: item, isAdhoc: isAdhoc });
          } else if (item.ChekedInStatus === true) {
            props.navigation.navigate('StoreList', { empData: item, isAdhoc: isAdhoc });
          } else {
            notify("You have some Checked In data for other employee.");
          }
        } else {
          notify("You have some Checked In data for other employee.");
        }

      } catch (err) {
        console.error('Error during check-in validation:', err);
        notify("Something went wrong while checking status.");
      }
    };

    checkAndNavigate();
  }, [item, hasCheckedInEmployee, props]);


  async function checkStoreCheckIn(empData1, props) {
    console.log("Get data callled dddd", empData1, isAdhoc);
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    let columKey = loginDetails?.Designation == "Supervisor" ? "MerchandiserId" : "EmpId";
    let q = '';

    const configData = (() => {
    try {
      return typeof props.ManagerAppConfig === "string"
        ? JSON.parse(props.ManagerAppConfig)
        : props.ManagerAppConfig;
    } catch (e) {
      return null;
    }
  })();


  const configArray = configData?.ManagerAppConfig ?? [];

  const currentConfig = configArray.find(
    item => item.Designation?.toLowerCase() === loginDetails.Designation?.toLowerCase()
  );

  const storewisePjp = currentConfig?.StorewisePJP;

  console.log("currentConfig:=>", currentConfig);
  console.log("storewisePjp:=>", storewisePjp);

    var tables = [
      'Sup_AdhocJourneyPlan',
      'Sup_NPNDStore',
      'Sup_JourneyPlan'
    ];


    if (storewisePjp === true) {
      tables = [
        'Sup_JourneyPlanStorewiseSup_Adhoc',
        'Sup_NPNDStore',
        'Sup_JourneyPlanStorewiseSup'
      ];
    }

    const whereClause = `VisitDate='${d2}' AND UploadStatus='I' AND ${columKey} != '${empData1?.EmpId}' `;

    const existingTables = [];

    // Check which tables exist
    for (const table of tables) {
      const exists = await new Promise((resolve) => {
        db.transaction(tx => {
          tx.executeSql(
            `SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
            [table],
            (tx, res) => resolve(res.rows.length > 0),
            (tx, err) => {
              console.error(`Error checking table ${table}:`, err);
              resolve(false);
            }
          );
        });
      });

      if (exists) {
        existingTables.push(table);
      }
    }

    if (existingTables.length === 0) {
      console.log('No valid tables found.');
      return [];
    }

    const unionQuery = existingTables
      .map(table => `SELECT * FROM ${table} WHERE ${whereClause}`)
      .join(' UNION ');
    // Run the final query
    console.log("unionQuery", unionQuery, d2, empData1?.EmpId)
    return new Promise((resolve, reject) => {
      db.transaction(tx => {
        tx.executeSql(
          unionQuery,
          [],
          (tx, res) => {
            const result = [];
            for (let i = 0; i < res.rows.length; i++) {
              console.log("unionQuery",)
              result.push(res.rows.item(i));
            }
            resolve(result);
          },
          (tx, err) => {
            console.error('Union query failed:', err);
            reject(err);
          }
        );
      });
    });
  }


  return (
    <TouchableOpacity
      style={customStyle.storel}
      key={props.index}
      onPress={() => { gotoPage(item) }}>
      <View style={customStyle.storel_card_outer}>
        <View style={customStyle.storel_card}>
          <View style={customStyle.storel_card_content}>
            <Text style={customStyle.storel_card_title}>{item.EmployeeName}</Text>
          </View>
        </View>
        <View style={customStyle.storel_details}>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{'Employee Id:'}</Text>
              <Text style={customStyle.storel_codeText}>{item.EmpId}</Text>
            </View>
          </View>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{'User Id:'}</Text>
              <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item.UserId}</Text>
            </View>
          </View>
          {
            (item.ChekedInStatus == true) &&
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
              <FontAwesome style={customStyle.storel_codeIcon} color={PageTheme.$red} name='connectdevelop' />
              <View style={[customStyle.storel_codeCon]}>
                <Text style={[customStyle.storel_codeTextRed,]}>{'You have some Checked In data for this employee'}</Text>
              </View>
            </View>
          }
        </View>
      </View>
    </TouchableOpacity>
  );
});

function TeamList(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 [loaderTitle, setLoaderTitle] = useState();
  const [processing, setProcessing] = useState((props.isDataDownloaded ? true : false));
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [nodataFound, setNodataFound] = useState(false);
  const [showStoreVisitModal, setShowStoreVisitModal] = useState(false);
  const [showGeoTagModal, setShowGeoTagModal] = useState(false);
  const [showDistanceModal, setShowDistanceModal] = useState(false);
  const [currentStore, setCurrentStore] = useState({});
  const [storeDistance, setStoreDistance] = useState('0 M');
  const [storeDistanceinM, setStoreDistanceinM] = useState(0);
  const [showAlert, setShowAlert] = useState(false);
  const [checkOutStore, setCheckOutStore] = useState({});
  const [rerenderdata, setrerenderdata] = useState(false);
  const [EmployeesList, setEmployeesList] = useState([]);
  const [globalEmplist, setGlobalEmplist] = useState([]);

  const [globalStorelist, setGlobalStorelist] = useState([]);
  const [cancelCheckOutStore, setCancelCheckOutStore] = useState({});
  const [showCancelCIModal, setShowCancelCIModal] = useState(false);
  const [searchedItem, setSearchedItem] = useState('');


  const [CheckOutImage, setCheckOutImage] = useState('');
  const [CheckOutImagePath, setCheckOutImagePath] = useState('');
  const [CheckOutImageModal, setCheckOutImageModal] = useState(false);
  const [CheckOutLoc, setCheckOutLoc] = useState({});
  const [showImageSaveOp, setShowImageSaveOp] = useState(true);
  const [showCamera, setShowCamera] = useState(false);
  const [GeoFenceEnable_Checkout, setGeoFenceEnable_Checkout] = useState(false);
  const [GeoFenceRadius_Checkout, setGeoFenceRadius_Checkout] = useState('');
  const [isCheckIn, setisCheckIn] = useState(false)

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

    if (props.isDataDownloaded == true && !props.isAttendanceMarked) {
      props.navigation.pop(); props.navigation.push('Attendance');
    }
    else {
      // checkLocalData();

      const FocusUnsubscribe = props.navigation.addListener('focus', () => { checkLocalData(); });

      return function cleanup() {
        FocusUnsubscribe();
        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);
    let params = props.route.params ? props.route.params : {};
    let isAdhoc = params.isAdhoc || false;
    console.log("isAdhoc===", isAdhoc)
    setIsAdhocScreen(isAdhoc);

    var q = '';
    if (isAdhoc == true) {
      q = `Select * from Sup_TeamList where TodayPJP='N'`;
    }
    else {
      q = `Select * from Sup_TeamList where TodayPJP='Y'`;
    }
    console.log("teamlist q:", q);
    await db.transaction(async function (txn) {
      await txn.executeSql(q, [], async function (txn2, txnres2) {
        console.log("teamlist length:", txnres2.rows.length);
        if (txnres2.rows.length > 0) {
          // show from local
          var storeArr = [];
          for (var i = 0; i < txnres2.rows.length; i++) {
            let data = txnres2.rows.item(i);
            console.log("data---", data)
            let ChekedInStatus = await getCheckInStatus(data);
            data['ChekedInStatus'] = ChekedInStatus;
            storeArr.push(data);

            if (i == (txnres2.rows.length - 1)) {
              setEmployeesList(storeArr);
              console.log("storeArr", storeArr);
              setGlobalEmplist(storeArr);
              setProcessing(false);
            }
          }
        }
        else {
          setProcessing(false); notify(ST.Nodatafound); setNodataFound(true);
        }
      }, function (txn2, txnerr) { console.log(txnerr); setProcessing(false); notify(ST.Nodatafound); setNodataFound(true); });
    });
  }



  // async function getCheckInStatus(emp){
  //     let {EmpId} =emp
  //     let d1=new Date();
  //     let d2=moment(d1).format('MM/DD/YYYY');
  //     return new Promise((resolve,reject)=>{
  //         db.transaction(async function (txn) { 

  //           //let join=`INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_JourneyPlan' `;
  //           let q=`Select t1.* from Sup_JourneyPlan t1 where t1.VisitDate='${d2}' and t1.MerchandiserId='${EmpId}' and t1.UploadStatus='I'`

  //           //let join2=`INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Sup_AdhocJourneyPlan' `;
  //           let q2=`Select t1.* from Sup_AdhocJourneyPlan t1 where t1.VisitDate='${d2}'  and t1.MerchandiserId='${EmpId}' and t1.UploadStatus='I'`

  //           await txn.executeSql(q,[],async function (txn2, txnres2) {           
  //               if(txnres2.rows.length>0){ 
  //                 // show from local
  //                 resolve(true);      
  //               }
  //               else{            
  //                 await txn.executeSql(q2,[],async function (txn2, txnres3) {           
  //                   if(txnres3.rows.length>0){ 
  //                     // show from local
  //                     resolve(true);      
  //                   }
  //                   else{   
  //                     resolve('');
  //                   }
  //                 },function(txn2,txnerr){console.log(txnerr);resolve('');  });
  //               }
  //           },function(txn2,txnerr){console.log(txnerr);resolve(''); });

  //         }); 

  //     }).then((val)=>{
  //       return val;
  //     }).catch((err)=>{
  //       return false;
  //     });
  // }

  const getCheckInStatus = async (emp) => {
    const { EmpId } = emp;
    const d2 = moment(new Date()).format('MM/DD/YYYY');

    return new Promise((resolve) => {
      db.transaction(async (txn) => {
        const q1 = `Select t1.* from Sup_JourneyPlan t1 where t1.VisitDate='${d2}' and t1.MerchandiserId='${EmpId}' and t1.UploadStatus='I'`;
        const q2 = `Select t1.* from Sup_AdhocJourneyPlan t1 where t1.VisitDate='${d2}' and t1.MerchandiserId='${EmpId}' and t1.UploadStatus='I'`;

        await txn.executeSql(q1, [], async (txn2, txnres1) => {
          if (txnres1.rows.length > 0) {
            resolve(true);
          } else {
            await txn.executeSql(q2, [], (txn2, txnres2) => {
              resolve(txnres2.rows.length > 0);
            });
          }
        });
      });
    });
  };




  function FilterStores(searchedQry) {
    searchedQry = searchedQry.toLowerCase();
    console.log('searchedQry', searchedQry);
    let arr = []
    if (searchedQry != null && searchedQry != '') {
      globalEmplist.map((item, index) => {
        let { EmpId, EmployeeName } = item;
        if (EmployeeName.toLowerCase().includes(searchedQry) || JSON.stringify(EmpId).toLowerCase().includes(searchedQry)) {
          arr.push(item);
        }
      });
    }
    else {
      // arr=globalStorelist;
      arr = globalEmplist;  // search fixed 
    }
    setEmployeesList(arr);
    setrerenderdata(!rerenderdata)
  }






  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')} />
      <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 && !props.isAttendanceMarked &&
            <NoAttendance {...props} />
          }
          {props.isDataDownloaded == true && props.isAttendanceMarked == true && props.isEntryAllow == false &&
            <NoAttendance {...props} msg={"You have marked your attendance and you are not allowed to fill data now! "} />
          }

          <View style={[customStyle.storelist_parentwrap]}>


            {/* <View style={customStyle.storeTab_Con}>
          <ScrollView style={customStyle.storeTab_MenuCon} contentContainerStyle={customStyle.storeTab_Menu} horizontal={true}>
            <TouchableOpacity style={[customStyle.storeTab_pill,(!isAdhocScreen?customStyle.storeTab_pillActive:{})]} onPress={()=>{props.navigation.pop();props.navigation.push('TeamList')}}>
              <Text style={[customStyle.storeTab_pillText,(!isAdhocScreen?customStyle.storeTab_pillActiveText:{color:PageTheme.$text_color})]}>{ST.Planned}</Text>
            </TouchableOpacity>
            <TouchableOpacity style={[customStyle.storeTab_pill,(isAdhocScreen?customStyle.storeTab_pillActive:{})]} onPress={()=>{props.navigation.pop();props.navigation.push('TeamList',{'isAdhoc': true})}}>
              <Text style={[customStyle.storeTab_pillText,(isAdhocScreen?customStyle.storeTab_pillActiveText:{color:PageTheme.$text_color})]}>{ST.Adhoc}</Text>
            </TouchableOpacity>
          </ScrollView>
          </View> */}

            <HeaderTabsTeam {...props} isAdhocScreen={isAdhocScreen} />

            <View style={customStyle.storel_searchbar}>
              <TextInput
                style={[customStyle.storel_searchInput]}
                placeholder={'Search by Employee Id, Employee Name'}
                placeholderTextColor={PageTheme.$placeholder_color}
                value={searchedItem}
                onChangeText={(val) => { setSearchedItem(val); FilterStores(val) }}
                autoComplete='off'
              />
              <TouchableOpacity style={customStyle.storel_searchBtn} onPress={() => { FilterStores(searchedItem) }}>
                <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
              </TouchableOpacity>
            </View>

            {nodataFound &&
              <View style={customStyle.noDataCon}>
                <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
              </View>
            }
            {(props.isDataDownloaded == true && props.isAttendanceMarked == true && !nodataFound) &&
              <View style={customStyle.storel_Con}>
                <FlatList
                  data={EmployeesList}
                  extraData={rerenderdata}
                  style={customStyle.listcon}
                  initialNumToRender={4}
                  contentContainerStyle={customStyle.iteml_con}
                  renderItem={({ item, index, separators }) => {
                    return (
                      <EmployeeItem  {...props} item={item} index={index} isAdhocScreen={isAdhocScreen} list={EmployeesList} StaticText={ST} />
                    );
                  }}
                />
              </View>
            }
          </View>


        </View>
      </LinearGradient>

    </Container>
  );
}



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