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, validateNumber, ValidateEmail } 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-geolocation-service';
import { getAvailblQuery, getIfAvlbl, getIfKPIDone, getQuery, Q_getMyStoresList, Q_MenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { uploadAllData, uploadAllImages, uploadStoreStatus } from '../constants/uploadData';
import { PrimaryTheme } from '../styles/Themes';
import NetworkStatusBar from '../components/NetworkStatusBar';
import * as RNFS from 'react-native-fs';
import ModalSelector from 'react-native-modal-selector';

import CameraImg2 from '../assets/performics/camera_icon.svg';
import CustomCamera from '../components/Camera';
import GradientButton from '../components/gradientButton';
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import cameraImg from '../assets/performics/camera_front_image.svg'


function StoreProfileScreen(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("Loading...");
  const [processing, setProcessing] = useState(false);
  const [rerenderdata, setrerenderdata] = useState(0);
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [isBeatPlan, setIsBeatPlan] = useState(false);
  const [storeData, setStoreData] = useState({});


  const [cityList, setCityList] = useState([]);
  const [storeTypeList, setStoreTypeList] = useState([]);
  const [ChainList, setChainList] = useState([]);
  const [StoreCategory, setStoreCategory] = useState([]);
  const [StoreClassList, setStoreClassList] = useState([]);
  const [DistributorList, setDistributorList] = useState([]);
  const [ChannelList, setChannelList] = useState([]);

  const [AllFormData, setAllFormData] = useState({});
  const [showCamera, setShowCamera] = useState(false);
  const [showImg, setShowImg] = useState(false);
  const [ImgURI, setImgURI] = useState("");
  const [StoreImage, setStoreImage] = useState('');
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

  const [IsEnableSubmit, setIsEnableSubmit] = useState(false);

  const [isNonMerchan, setIsNonMerchan] = useState(false);
  const [isNonProg, setIsNonProg] = useState(false);

  let d1 = new Date();
  let today = moment(d1).format('MM/DD/YYYY');

  useEffect(() => {
    setLoaderTitle(ST.Loading + '...')
    let params = props.route.params ? props.route.params : {};
    let storeData1 = params.storeData || {};
    // console.log('storeData1:',storeData1);
    let isAdhoc = params.isAdhoc || false;
    let isBeat = params.isBeat != null ? params.isBeat : false;
    let isNonMerchan1 = params.isNonMerchans != null ? params.isNonMerchans : false;
    let isNonProgam = params.isNonProgs != null ? params.isNonProgs : false;
    setIsAdhocScreen(isAdhoc);
    setIsBeatPlan(isBeat);
    setIsNonMerchan(isNonMerchan1);
    setIsNonProg(isNonProgam)
    setStoreData(storeData1);

    let st2 = Object.assign({ 'test': '1' }, storeData1);
    setAllFormData(st2); //Assigning current Store Data to FormData to be filled or changed

    validateForm(true, storeData1);
  }, [])


  async function validateForm(isCheck = false, storeData1 = {}) {
    let isValid = true;
    let data = isCheck == true ? storeData1 : AllFormData;
    let { StoreName, Address, Location, Pincode, ContactPerson, Phone, Mobile, GSTno, Email } = data;

    if (StoreName == '' || StoreName == null) {
      isValid = false;
      notify('Please enter Store Name', 'SHORT');
    }
    else if (Address == '' || Address == null) {
      isValid = false;
      notify('Please enter Address ', 'SHORT');
    }
    else if(GSTno!=null && GSTno!='' && GSTno.length<15){
      isValid=false;
      notify('Please Fill correct GST No.','SHORT');
    }
    else if (Location == '' || Location == null) {
      isValid = false;
      notify('Please enter Location ', 'SHORT');
    }
    else if (Pincode == '' || Pincode == null) {
      isValid = false;
      notify('Please enter Pincode ', 'SHORT');
    }
    else if (Pincode.length != 6) {
      isValid = false;
      notify('Please enter valid Pincode ', 'SHORT');
    }
    else if ((Phone != null && Phone != '') && Phone.length != 10) {
      isValid = false;
      notify('Please enter valid Contact Number | Mobile Number', 'SHORT');
    }
    // else if((Mobile!=null && Mobile!='') && Mobile.length!=10 ){
    //   isValid=false;
    //   notify('Please enter valid Mobile Number','SHORT');
    // }
    else if ((Email != '' && Email != null) && !ValidateEmail(Email)) {
      isValid = false;
      notify('Please enter valid Email', 'SHORT');
    }
    console.log('isValid:', Pincode, isValid);

    if (isCheck == true && isValid == false) {
      setIsEnableSubmit(true);
    }
    return isValid;
  }


  function onStoreDataChange(val, key, type = '') {

    if (val != '') {
      let isValid = validateNumber(val, type);
      if (!isValid) {
        return;
      }
    }

    let allData = AllFormData;
    allData[key] = val;
    console.log('onStoreDataChange:', Object.keys(storeData).length)

    if (storeData[key] != val) {
      setIsEnableSubmit(true);
    }
    else {
      let i = 0;
      for (let key1 in storeData) {
        console.log('key1', key1, storeData[key1], allData[key1], storeData[key1] != allData[key1])
        if (storeData[key1] != allData[key1]) {
          console.log('enableSUbmitBtn')
          setIsEnableSubmit(true);
          break;
        }
        if (i == Object.keys(storeData).length - 1) {
          console.log('disableSUbmitBtn')
          setIsEnableSubmit(false);
        }
        i++;
      }
    }

    setAllFormData(allData);
    setHasUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }

  const onSubmitData = async () => {
    if (IsEnableSubmit) {
      let isValid = await validateForm();
      if (isValid) {
        setLoaderTitle('Updating Store Profile!...');
        setProcessing(true);


        let val = ` ('${storeData.StoreId}', '${AllFormData.StoreName}','${AllFormData.Address}','${AllFormData.GSTno}','${AllFormData.ContactPerson}','${AllFormData.Phone}', '','${AllFormData.Location}','${AllFormData.Pincode}','${AllFormData.Email}','${today}', '${today}')`;
        let q = `INSERT INTO ${AppTables.STORE_PROFILE}(STORE_ID ,STORE_NAME ,ADDRESS ,GSTNO ,CONTACT_PERSON ,PHONE ,MOBILE ,LOCATION ,PINCODE , EMAIL ,VISIT_DATE ,ADDED_DATE)
          values ${val}`;
        db.transaction(function (txn) {
          txn.executeSql(`Delete from ${AppTables.STORE_PROFILE} where STORE_ID='${storeData.StoreId}' and VISIT_DATE='${today}'`, [], function (txn1, txnres) {

            txn.executeSql(q, [], function (txn1, txnres) {
              console.log('Store Profile is added');


              // update data in storeList
              let tbname = (isBeatPlan == true ? 'JourneyPlan_RouteWise' : (isAdhocScreen == true ? 'Adhoc_JourneyPlan' : (isNonMerchan == true ? 'NonMerchandising_JourneyPlan' : isNonProg == true ? 'NonProgram_JourneyPlan' : 'Mapping_JourneyPlan')))
              let update_val = `StoreName='${AllFormData.StoreName}',Address='${AllFormData.Address}',GSTno='${AllFormData.GSTno}',ContactPerson='${AllFormData.ContactPerson}',Phone='${AllFormData.Phone}',Mobile='${AllFormData.Mobile}',Location='${AllFormData.Location}',Pincode='${AllFormData.Pincode}',Email='${AllFormData.Email}' `;
              let q2 = `Update ${tbname} set  ${update_val} where StoreId='${storeData.StoreId}' and VisitDate='${today}' `;
              txn.executeSql(q2, [], function (txn1, txnres) {

                console.log('Store Profile is updated');
                setProcessing(false);
                gotoDailyMenu(true);
              }, function (Etxn, err) {
                console.log('err:', err);
                notify('Cannot Add Store Profile!');
                setProcessing(false);
              });
            }, function (Etxn, err) {
              console.log('err:', err);
              notify('Cannot Add Store Profile!');
              setProcessing(false);
            });
          }, function (Etxn, err) {
            console.log('err:', err);
            notify('Cannot Add Store Profile!');
            setProcessing(false);
          });

        });

      }
    }
    else {
      gotoDailyMenu();
    }
  }

  const gotoDailyMenu = (updated = false) => {
    let data = updated ? AllFormData : storeData;
    let s_screen = "StoreDailyMenu"
    if (props.ShowStoreChecklist == true) {
      s_screen = "StoreChecklist";
    } else if (props.ShowReportAfterCheckIn == true) {
      s_screen = "ReportsMenu";
    }
    
    props.navigation.replace(s_screen, { storeData: data, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, "isNonMerchans": isNonMerchan, isNonProgs: isNonProg, '_fromStoreWise': true });
  }

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      <CustomHeader {...props} showaddstore={true} title={"Store Profile"} />

      <CustomCamera cameraType={'back'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: Store Profile'} 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.STp_hdrParent]}>
            <View style={[customStyle.STp_Hdr]}>
              <Text style={customStyle.STp_HdrText}>Store Profile</Text>
            </View>
          </View>
          <ScrollView
            style={customStyle.STp_ContentOuter}
            contentContainerStyle={customStyle.STp_ContentInner}
          >
            {rerenderdata == rerenderdata &&
              <View style={[customStyle.STp_Card]}>
                <View style={[customStyle.STp_card_outer,]}>
                  <View style={[customStyle.STp_storeDetails,]}>
                    <View style={customStyle.storel_code}>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeBorder, customStyle.storel_codeConAddr]}>
                        <Text style={customStyle.storel_codeLbl}>{ST.StoreId + ':'}</Text>
                        <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                      </View>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                        <Text style={customStyle.storel_codeLbl}>{ST.StoreType + ':'}</Text>
                        <Text style={[customStyle.storel_codeText, { width: '50%' }]}>{storeData.StoreType}</Text>
                      </View>
                    </View>
                    <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                        <Text style={customStyle.storel_codeLbl}>{ST.StoreCode + ':'}</Text>
                        <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{storeData.StoreCode == "undefined" ? "" : storeData.StoreCode}</Text>
                      </View>
                    </View>
                    <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                        <Text style={customStyle.storel_codeLbl}>{'City Name:'}</Text>
                        <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{storeData.CityName}</Text>
                      </View>
                    </View>
                    <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                        <Text style={customStyle.storel_codeLbl}>{'Tax Type:'}</Text>
                        <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{AllFormData.TaxType}</Text>
                      </View>
                    </View>
                    <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                        <Text style={customStyle.storel_codeLbl}>{'Chain Name:'}</Text>
                        <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{AllFormData.ChainName}</Text>
                      </View>
                    </View>
                    <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                        <Text style={customStyle.storel_codeLbl}>{'Channel Id:'}</Text>
                        <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{AllFormData.ChannelId}</Text>
                      </View>
                    </View>
                    <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                        <Text style={customStyle.storel_codeLbl}>{'Store Category:'}</Text>
                        <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{AllFormData.StoreCategory}</Text>
                      </View>
                    </View>
                    <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                        <Text style={customStyle.storel_codeLbl}>{'Store Class:'}</Text>
                        <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{AllFormData.StoreClass}</Text>
                      </View>
                    </View>

                  </View>
                  <View style={[customStyle.STp_form]}>
                    <View style={customStyle.AddStockM_row} >
                      <Text style={customStyle.AddStockM_label}>{"Name"}</Text>
                      <View style={customStyle.AddStockM_col} >
                        <TextInput
                          style={[customStyle.AddStockM_InputStyle]}
                          placeholder=""
                          autoComplete='off'
                          placeholderTextColor={PageTheme.$placeholder_color}
                          value={(AllFormData.StoreName || '')}
                          onChangeText={(val) => { onStoreDataChange(val, 'StoreName', 'text') }}
                        />
                      </View>
                    </View>
                    <View style={customStyle.AddStockM_row} >
                      <Text style={customStyle.AddStockM_label}>{"Address"}</Text>
                      <View style={customStyle.AddStockM_col} >
                        <TextInput
                          style={[customStyle.AddStockM_InputStyle]}
                          placeholder=""
                          autoComplete='off'
                          placeholderTextColor={PageTheme.$placeholder_color}
                          value={(AllFormData.Address || '')}
                          onChangeText={(val) => { onStoreDataChange(val, 'Address', 'text') }}
                        />
                      </View>
                    </View>
                    <View style={customStyle.AddStockM_row} >
                      <Text style={customStyle.AddStockM_label}>{"GST No"}</Text>
                      <View style={customStyle.AddStockM_col} >
                        <TextInput
                          style={[customStyle.AddStockM_InputStyle]}
                          placeholder=""
                          autoComplete='off'
                          placeholderTextColor={PageTheme.$placeholder_color}
                          value={AllFormData.GSTno || ''}
                          onChangeText={(val) => {
                            // Remove all non-alphanumeric characters
                            const cleaned = val.replace(/[^a-zA-Z0-9]/g, '');
                            onStoreDataChange(cleaned, 'GSTno', 'text');
                          }}
                          maxLength={15}
                        />
                      </View>
                    </View>
                    <View style={customStyle.AddStockM_row} >
                      <Text style={customStyle.AddStockM_label}>{"Location"}</Text>
                      <View style={customStyle.AddStockM_col} >
                        <TextInput
                          style={[customStyle.AddStockM_InputStyle]}
                          placeholder=""
                          autoComplete='off'
                          placeholderTextColor={PageTheme.$placeholder_color}
                          value={(AllFormData.Location || '')}
                          onChangeText={(val) => { onStoreDataChange(val, 'Location', 'text') }}
                        />
                      </View>
                    </View>
                    <View style={customStyle.AddStockM_row} >
                      <Text style={customStyle.AddStockM_label}>{"Pin Code"}</Text>
                      <View style={customStyle.AddStockM_col} >
                        <TextInput
                          style={[customStyle.AddStockM_InputStyle]}
                          placeholder=""
                          autoComplete='off'
                          placeholderTextColor={PageTheme.$placeholder_color}
                          keyboardType={'number-pad'}
                          maxLength={6}
                          value={(AllFormData.Pincode != null ? AllFormData.Pincode + '' : '')}
                          onChangeText={(val) => { onStoreDataChange(val, 'Pincode', 'numeric') }}
                        />
                      </View>
                    </View>
                    <View style={customStyle.AddStockM_row} >
                      <Text style={customStyle.AddStockM_label}>{"Contact Person"}</Text>
                      <View style={customStyle.AddStockM_col} >
                        <TextInput
                          style={[customStyle.AddStockM_InputStyle]}
                          placeholder=""
                          autoComplete='off'
                          placeholderTextColor={PageTheme.$placeholder_color}
                          value={(AllFormData.ContactPerson || '')}
                          onChangeText={(val) => { onStoreDataChange(val, 'ContactPerson', 'text') }}
                        />
                      </View>
                    </View>
                    <View style={customStyle.AddStockM_row} >
                      <Text style={customStyle.AddStockM_label}>{"Contact Number | Mobile Number"}</Text>
                      <View style={customStyle.AddStockM_col} >
                        <TextInput
                          style={[customStyle.AddStockM_InputStyle]}
                          placeholder=""
                          autoComplete='off'
                          placeholderTextColor={PageTheme.$placeholder_color}
                          keyboardType={'number-pad'}
                          maxLength={10}
                          value={(AllFormData.Phone != null ? AllFormData.Phone + '' : '')}
                          onChangeText={(val) => { onStoreDataChange(val, 'Phone', 'numeric') }}
                        />
                      </View>
                    </View>
                    {/* <View style={customStyle.AddStockM_row} >
                        <Text style={customStyle.AddStockM_label}>{"Mobile Number"}</Text>
                        <View style={customStyle.AddStockM_col} >
                          <TextInput 
                            style={[customStyle.AddStockM_InputStyle]}
                            placeholder=""
                            autoComplete='off'
                            placeholderTextColor={PageTheme.$placeholder_color} 
                            keyboardType={'number-pad'}
                            maxLength={10}
                            value={(AllFormData.Mobile!=null?AllFormData.Mobile+'':'')}
                            onChangeText={(val)=>{onStoreDataChange(val,'Mobile','numeric')}}
                          />
                        </View>
                    </View> */}
                    <View style={customStyle.AddStockM_row} >
                      <Text style={customStyle.AddStockM_label}>{"Email"}</Text>
                      <View style={customStyle.AddStockM_col} >
                        <TextInput
                          style={[customStyle.AddStockM_InputStyle]}
                          placeholder=""
                          autoComplete='off'
                          placeholderTextColor={PageTheme.$placeholder_color}
                          value={(AllFormData.Email || '')}
                          onChangeText={(val) => { onStoreDataChange(val, 'Email', 'text') }}
                        />
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            }
          </ScrollView>

          <View style={customStyle.SChk_BtnWrapFlex}>
            <View style={[customStyle.SChk_BtnCol, customStyle.SChk_BtnCol1]}>
              {!IsEnableSubmit &&
                <View style={[customStyle.SChk_Btn]}>
                  <GradientButton {...props} title={'Skip'} onPress={() => { gotoDailyMenu() }} style={customStyle.SChk_BtnSave} />
                </View>
              }
              {IsEnableSubmit &&
                <View style={[customStyle.SChk_Btn]}>
                  <GradientButton {...props} title={'Skip'} onPress={() => { gotoDailyMenu() }} style={customStyle.SChk_BtnSave} disabled={true} colors={[PageTheme.$tertiary_color, PageTheme.$tertiary_color]} />
                </View>
              }
            </View>
            <View style={[customStyle.SChk_BtnCol, customStyle.SChk_BtnCol2]}>
              {/* {!IsEnableSubmit && 
                  <View style={[customStyle.SChk_Btn]}>
                    <GradientButton {...props} title={ST.Save} onPress={()=>{onSubmitData()}} style={customStyle.SChk_BtnSave} disabled={true} colors={[PageTheme.$tertiary_color,PageTheme.$tertiary_color]}/> 
                  </View>  
                  }
                  */}
              <View style={[customStyle.SChk_Btn]}>
                <GradientButton {...props} title={ST.Save} onPress={() => { onSubmitData() }} style={customStyle.SChk_BtnSave} />
              </View>
            </View>
          </View>
        </View>
      </LinearGradient>
    </Container>
  );
}



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