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, baseurl } from '../constants/constants';
import CustomHeader from '../components/customHeader';

import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';

import { AppTables } from '../constants/tableConstants';
import { _checkLocationPermission } from '../components/geolocation';

import CustomCamera from '../components/Camera';
import GradientButton from '../components/gradientButton';
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import { METHODS, getMethodName } from '../constants/methodNames';
import CustomModal from '../components/CustomModal';
import { useSafeAreaInsets } from 'react-native-safe-area-context';



function PrevStoreReason(props) {
  const route = useRoute();
  
  const insets = useSafeAreaInsets();
  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 [PrevStoreList, setPrevStoreList] = useState([]);
  const [StoreReason, setStoreReason] = useState([]);
  const [totalQtn, setTotalQtn] = useState(0);
  const [qad, setQad] = useState([]);




  const [AllFormData, setAllFormData] = useState({});
  const [showCamera, setShowCamera] = useState(false);

  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

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

  const [isNonMerchan, setIsNonMerchan] = useState(false);
  const [isNonProg, setIsNonProg] = useState(false);
  const [filtervalue, setFilterValue] = useState({});
  const [showAlert, setShowAlert] = useState(false);
  const [EntryAllow, setEntryAllow] = useState(false);

  const [isDisable, setDisable] = useState(false);



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

  useEffect(() => {
  const init = async () => {
    try {
      setProcessing(true);
      setLoaderTitle(ST.Loading + '...');

      const params = props.route.params || {};
      const storeData1 = params.storeData || {};

      setIsAdhocScreen(params.isAdhoc || false);
      setIsBeatPlan(params.isBeat ?? false);
      setIsNonMerchan(params.isNonMerchans ?? false);
      setIsNonProg(params.isNonProgs ?? false);
      setStoreData(storeData1);
      setAllFormData({ test: '1', ...storeData1 });

      await Promise.all([
        getData(storeData1),
        get_OQAD()
      ]);
    } catch (e) {
      console.log("Init error", e);
    } finally {
      setProcessing(false); // ✅ only here
    }
  };

  init();
}, []);


  async function getData() {
  try {
    const token = await get_item('loginToken');
    const loginInfo = JSON.parse(await get_item('loginInfo'));

    const url = (props.baseurl || baseurl) +
      getMethodName(METHODS.DOWNLOADJSON_METHOD);

    const req1 = {
      Downloadtype: 'PreviousDay_PendingJourneyPlan',
      username: loginInfo.UserId,
      empid: ""
    };

    const req2 = {
      Downloadtype: 'Non_Working_Reason',
      username: loginInfo.UserId,
      empid: ""
    };

    const [res1, res2] = await Promise.all([
      getDownloadJson(url, req1),
      getDownloadJson(url, req2)
    ]);

    let EntryAllowFlag = false;

    if (res1?.PreviousDay_PendingJourneyPlan) {
      const list = res1.PreviousDay_PendingJourneyPlan;
      EntryAllowFlag = list.some(i => i?.CoveredStore == 1);
      setEntryAllow(EntryAllowFlag);
      setPrevStoreList(list);
    }

    if (res2?.Non_Working_Reason) {
      const filtered = res2.Non_Working_Reason.filter(r =>
        r.PreviousVisit === true &&
        (EntryAllowFlag ? r.EntryAllow === true : true)
      );
      setStoreReason(filtered);
    }

  } catch (err) {
    console.log("getData error:", err);
  }
}



  function _render_Alert() {
    return (
      <CustomModal
        style={customStyle.storelVisitM_Style}
        titleStyle={customStyle.storelVisitM_titleStyle}
        title={'Do you really want to save data?'}
        showModal={showAlert}
      >
        <View style={customStyle.storelVisitM_options}>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowAlert(false) }}>
            <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
          </TouchableOpacity>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { saveData() }}>
            <Text style={customStyle.storelVisitM_op_btnText}>Yes</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }
  async function validate() {
    let isValid = true;

    await Promise.all(
      PrevStoreList.map(async (item, index) => {
        if (isValid == true) {
          if (!Boolean(item.Reason) && item.ReasonId == null || item.ReasonId == '') {
            notify('Please select reason for store Id ' + item.StoreId, 'SHORT');
            isValid = false;
          }
        }
      })
    );

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

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

  
  async function saveData() {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    setShowAlert(false);
    setProcessing(true);
    setLoaderTitle('Uploading Data...');

    let storeInfo = PrevStoreList
    let arr = []

    storeInfo?.map((item, i) => {
      let itemObj = {
        MID: item.MID,
        StoreId: item.StoreId,
        VisitDate: item.VisitDate,
        EmpId: item.EmpId,
        ReasonId: item.ReasonId,
        UserId: props.UserId,
        AppVersion: AppVersion
      };
      arr.push(itemObj);
    })


    let postData = {
      "MID": 0,
      "Keys": "PrevStoreNonCovStatus",
      "JsonData": JSON.stringify(arr),
      "UserId": props.UserId,
    };

    console.log("jsondataaa:", postData)


    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    await UploadData2(url, postData)
      .then(async (res) => {
        console.log('res: 12', res);
        if (res?.UploadJsonResult == "Success") {
          notify('Store Status Uploaded Succesfully', 'SHORT');
          let prevStoreObj = {
            Status: true,
            visiteDate: d2
          }
          let strObj = JSON.stringify(prevStoreObj)
          await set_item('prevStoreStatus', strObj);
          setProcessing(false);
          setShowAlert(false)
          gotoScreen(true, totalQtn);
        }
        else {
          setShowAlert(false)
          setProcessing(false);
        }
      })
      .catch((err) => {
        console.log(err); setProcessing(false);
      });

  }


  async function get_OQAD() {
    let token = await get_item('loginToken');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    var data = { Downloadtype: 'OQAD', username: loginDetails.UserId, empid: '', token: token, };

    const url = (props.baseurl || baseurl) + getMethodName(METHODS.DOWNLOADJSON_METHOD);
    console.log(url, data);
    await getDownloadJson(url, data)
      .then(async (res) => {
        console.log('res:', res);
        if (res.OQAD != null) {
          let QAD_arr = res.OQAD || [];
          let allQADS = [];

          var qad_data = {};
          var qids = [];
          for (var i = 0; i < QAD_arr.length; i++) {
            let data = QAD_arr[i];
            let isadded = false;


            if (qids.indexOf(data.QuestionId) < 0) {
              if (Object.keys(qad_data).length > 0) allQADS.push(qad_data);
              qids.push(data.QuestionId)
              qad_data = {};
              qad_data['QuestionId'] = data.QuestionId;
              qad_data['Question'] = data.Question;
              qad_data['Options'] = [{ 'AnswerId': data.AnswerId, 'Answer': data.Answer }];
              if (data.RightAnswer == true) qad_data['Answer'] = data.AnswerId;

            }
            else {
              let ops = qad_data['Options'] || [];
              ops.push({ 'AnswerId': data.AnswerId, 'Answer': data.Answer });
              if (data.RightAnswer == true) qad_data['Answer'] = data.AnswerId;

            }

            if (i == QAD_arr.length - 1) {
              allQADS.push(qad_data);
              setQad(allQADS);
              setTotalQtn(allQADS.length);
              setTimer(false, false, allQADS);
            }
          }

        }
        else if (typeof (res) == 'object' && res.length > 0 && res[0].Result != null && res[0].Result.includes('No Data')) {
          // OQAD Not Found
         // goToHome();
         setTotalQtn(-1);
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
      });

  }

  const gotoScreen = (flag,totalQtn) => {
    console.log('totalQtn:', totalQtn, 'flag:', flag);
    if (flag == true && totalQtn < 0) {
      props.navigation.replace("NoticeBoard");
    }
    else{
      props.setLoginExists(false);
      props.navigation.replace("One_QAD", { UserData: storeData, TodayLogin: true });
    }

  }

  function onselectionChange(option, keyLbl, keyVal, otherData) {
    console.log("onselectionChange:", option, keyLbl, keyVal, otherData)
    // let data=AddStoreinfoFormData;
    let data = PrevStoreList || [];
    let optionDAta = otherData?.filterData || []

    let optionObj = optionDAta[option?.key]

    // if(EntryAllow){
    // optionObj?.EntryAllow==false || EntryAllow
    if (optionObj?.EntryAllow == false) {

      data = data?.map((item, i) => {
        let obj = item;
        obj[keyVal] = option.value;
        obj[keyLbl] = option.label;
        // data[index]=obj
        return obj
      })
      setDisable(true)
    } else {
      let index = otherData?.index
      if (isDisable) {
        data = data?.map((item, i) => {
          let obj = item;
          if (index == i) {
            obj[keyVal] = option.value;
            obj[keyLbl] = option.label;
          } else {
            obj[keyVal] = null;
            obj[keyLbl] = null;
          }
          return obj
        })
      } else {
        // let index=otherData?.index
        let obj = data[index];
        obj[keyVal] = option.value;
        obj[keyLbl] = option.label;
        data[index] = obj
      }
      setDisable(false)
    }

    setPrevStoreList(data)
    // BgAddVisFormData(data)
    // // setHasUnsavedChanges(true);
    // BgUnsavedChanges(true)
    setrerenderdata(!rerenderdata);

  }

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      <CustomHeader {...props} showaddstore={true} title={"Previous Store status"} />
      {_render_Alert()}
      <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}>Previous day non-working Store status</Text>
            </View>
          </View>
          <ScrollView
            style={customStyle.STp_ContentOuter}
            contentContainerStyle={customStyle.STp_ContentInner}
          >
            {rerenderdata == rerenderdata && PrevStoreList?.map((item, index) => {

              let filterData = StoreReason.filter((rs) => rs.ChannelId == item.ChannelId && rs.PreviousVisit == true);
              return (
                <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}>{item.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%' }]}>{item.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]}>{item.StoreCode == "undefined" ? "" : item.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}>{'Distributor Name:'}</Text>
                          <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item.DistributorName}</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]}>{item.CityName}</Text>
                        </View>
                      </View>
                      <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.storel_codeBorderBottom, customStyle.mt10]}>
                        <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                          <Text style={customStyle.storel_codeLbl}>{'Address:'}</Text>
                          <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item.Address}</Text>
                        </View>
                      </View>

                    </View>
                    <View style={[{ paddingHorizontal: 10, width: '100%' }]}>
                      <Text style={[customStyle.sform_label3, { marginTop: 0 }]}>Select Reason :</Text>
                      {CustomPicker(props, filterData, 'Reason', 'ReasonId', 'Reason', 'ReasonId', onselectionChange, { value: item?.Reason || '', otherData: { index, filterData } }, {}, {}, '', null, (index == 0 ? false : isDisable))}
                    </View>
                  </View>
                </View>
              )
            })
            }
          </ScrollView>

          {/* <View style={customStyle.SChk_BtnWrapFlex}>
            <View style={[customStyle.SChk_BtnCol, customStyle.SChk_BtnCol2]}>
              <View style={[customStyle.SChk_Btn]}>
                <GradientButton {...props} title={'Save'} onPress={() => { submit() }} />
              </View>
            </View>
          </View> */}
          <View 
  style={[
    customStyle.SChk_BtnWrapFlex,
    { paddingBottom: insets.bottom }
  ]}
>              
  <View style={[customStyle.SChk_BtnCol, customStyle.SChk_BtnCol2]}>
    <View style={[customStyle.SChk_Btn]}>
      <GradientButton 
        {...props} 
        title={'Save'} 
        onPress={submit}
      /> 
    </View> 
  </View>
</View>
        </View>
      </LinearGradient>
    </Container>
  );
}



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