import React, { useState, useEffect, useRef } 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, PermissionsAndroid, FlatList, Alert, Animated, AppState, Keyboard } 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, getKPIFields, marktext1, marktext2, resizeImage, restore_ImageWithMetaData, validateNumber } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr, common_ImagePath, ImageFolderPath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { Card, Menu, Switch } from 'react-native-paper';
import { AntDesign, Entypo, Feather, FontAwesome, Fontisto, MaterialCommunityIcons } from '../components/icons';
import { stat } from 'react-native-fs';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { SvgXml } from 'react-native-svg';
import { launchCamera, launchImageLibrary, CameraOptions } from 'react-native-image-picker';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';

import cameraImg from '../assets/performics/camera_front_image.svg'
import addImg from '../assets/performics/add_image.svg';
import CustomModal from '../components/CustomModal';
import { Q_getpaidvisibility } from '../constants/ConstantQueries';
import { Picker } from '@react-native-picker/picker';
import { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector'
import { CustomPicker } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import DateTimePicker from '@react-native-community/datetimepicker';

import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg4 from '../assets/performics/camera_asterisk.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';

// Feather

function BreakTime(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 animatedChoice = useRef(new Animated.Value(0)).current;

    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);

    const [ShowDatePicker1, setShowDatePicker1] = useState(false);
    const [ShowDatePicker, setShowDatePicker] = useState(false);
    const [currentMenu, setCurrentMenu] = useState({});
    const [brandData, setBrandData] = useState([]);
    const [rerenderdata, setrerenderdata] = useState(0);
    const [rerenderdata2, setrerenderdata2] = useState(0);
    // const [rerenderdata2, setrerenderdata2]= useState(false);

    const [AddVisibility, setAddVisibility] = useState([]);
    const [AddVisFormData, setAddVisFormData] = useState({});
    const [isAddVisPresent, setIsAddVisPresent] = useState(0);
    const [showAlert, setShowAlert] = useState(false);
    const [Categories, setCategories] = useState([]);
    const [BreakTypes, setBreakTypes] = useState([]);
    const [SubCategories, setSubCategories] = useState([]);
    const [Brands, setBrands] = useState([]);
    const [DisplayList, setDisplayList] = useState([]);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const [showCamera, setShowCamera] = useState(false);
    const [clickImageType, setClickImageType] = useState('1');
    const [toRemoveId, setToRemoveId] = useState('');
    const [toRemoveItem, setToRemoveItem] = useState({});
    const [showRemoveConfirm_M, setshowRemoveConfirm_M] = useState(false);
    const [showRAllC_M, setShowRAllC_M] = useState(false);
    const [KPIFields, setKPIFields] = useState([]);
    const [dateValue, setDateValue] = useState('');
    const [FromDate, setFromDate] = useState('');
    const [FromDate2, setFromDate2] = useState(new Date());

    const [ToDate, setToDate] = useState('');
    const [ToDate2, setToDate2] = useState(new Date());

    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [ImgMadCount, setImgMadCount] = useState({ img1: 0, img2: 0 });
    const [reportData, setReportData] = useState([]);
    const [IsDisable, setIsDisable] = useState(false);

    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef = React.useRef(AddVisibility);
    const StoreIdRef = React.useRef(null);
    const ScreenNameRef = React.useRef('');
    const VisFormDataRef = React.useRef(AddVisFormData);
    const isAddVisPresentRef = React.useRef(isAddVisPresent);
    const d1 = new Date();
    const d2 = moment(d1).format('MM/DD/YYYY');


    useEffect(() => {
        setLoaderTitle(ST.Loading + '...')
        let params = props.route.params ? props.route.params : {};
        let storeData1 = params.storeData || {};
        let menu1 = params.menu || {};
        let cameraAllow = storeData1.CameraAllow == 'true' || storeData1.CameraAllow == 1 ? true : false;
        setStoreCameraAllow(cameraAllow);

        let isAdhoc = params.isAdhoc || false;

        StoreIdRef.current = storeData1.StoreId
        ScreenNameRef.current = menu1.ScreenName
        setIsAdhocScreen(isAdhoc);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        console.log("storeData1---test--", storeData1)
        getData(storeData1, menu1);

        const AppStateSubscription = AppState.addEventListener('change', (pro) => { _handleAppStateChange(pro) });
        props.navigation.addListener('beforeRemove', onBeforeRemove);

        return function cleanup() {
            AppStateSubscription.remove();
            props.navigation.removeListener('beforeRemove', onBeforeRemove);
        };
    }, []);

    const _handleAppStateChange = async (nextAppState) => {
        console.log('getDAta-----bg-unsaved1')
        if (nextAppState == 'background' && hasUnsavedChangesRef.current == true) {
            console.log('getDAta-----bg-unsaved1', hasUnsavedChangesRef)
            let newData = {
                storeBGData: WindowDataRef.current,
                menuName: ScreenNameRef.current,
                StoreId1: StoreIdRef.current,
                AddFormData: VisFormDataRef.current,
                isVisPresent: isAddVisPresentRef.current,
                visiteDate: d2
            }
            let WindowsStr = await JSON.stringify(newData)
            console.log('getDAta-----bg-unsaved2', WindowsStr)
            //    await set_item('storeData',WindowsStr); 
        }
    }

    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [hasUnsavedChanges]);


    useEffect(() => {
        props.navigation.removeListener('beforeRemove', onBeforeRemove);
        props.navigation.addListener('beforeRemove', onBeforeRemove);
    }, [showCamera]);

    function BgUnsavedChanges(val) {
        hasUnsavedChangesRef.current = val
        setHasUnsavedChanges(val);
    }

    function BgWindowData(val) {
        WindowDataRef.current = val
        setAddVisibility(val);
    }

    function BgAddVisFormData(val) {
        VisFormDataRef.current = val
        setAddVisFormData(val);
    }

    function BgIsAddVisPresent(val) {
        isAddVisPresentRef.current = val
        setIsAddVisPresent(val);
    }


    function onBeforeRemove(e) {
        if (showCamera == true) {
            e.preventDefault();
            setShowCamera(false);
        }
        else {
            if (hasUnsavedChanges == true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else {
                return;
            }
        }
    }
    function onRemoveScreen(e) {
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
                {
                    text: ST.Cancel,
                    onPress: () => { },
                    style: "cancel"
                },
                {
                    text: ST.OK, onPress: async () => {
                        BgUnsavedChanges(false)
                        await clear_item('storeData')
                        setHasUnsavedChanges(false);
                        props.navigation.dispatch(e.data.action);
                    }
                }
            ]
        );
    }

    async function getData(storeData1, menu1) {
        try {
            let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;

            let AllKPIFields = await getKPIFields(menu1);
            setKPIFields(AllKPIFields);


            let isFromDateIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
            let isFromDateKPIObj = isFromDateIndex >= 0 ? AllKPIFields[isFromDateIndex] : {};
            let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;


            let TestData = [{
                BreakName: "Tea",
                BreakID: 2,
                MaxNumber: 2,
                MinNumber: 1,
            }, {
                BreakName: "Walk",
                BreakID: 3,
                MaxNumber: 2,
                MinNumber: 1,
            }]
            // setBreakTypes(TestData)

            await db.transaction(async function (txn) {

                // Master_Break(BreakId,Break_Name,Minimum,Maximum)
                let q = `Select * from Master_Break `;
                await txn.executeSql(q, [], async function (txn2, txnres2) {

                    if (txnres2.rows.length > 0) {
                        let arr = [];
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            let { BreakId, Break_Name, Minimum, Maximum } = data
                            let newobj = {
                                BreakName: Break_Name,
                                BreakID: BreakId,
                                MaxNumber: Maximum,
                                MinNumber: Minimum,
                            }
                            arr.push(newobj);
                            if (i == txnres2.rows.length - 1) { setBreakTypes(arr); console.log("newobj-------", arr) }
                        }
                    }
                }, function (txnE, txnerr) { console.log(txnerr); },);

                let q3 = `Select * from ${AppTables.BREAKTIME} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                await txn.executeSql(q3, [], async function (txn2, txnres2) {
                    if (txnres2.rows.length > 0) {
                        let arr = [], storeBGData1 = [], bgStoreJson = {};
                        for (var i = 0; i < txnres2.rows.length; i++) {
                            let data = txnres2.rows.item(i);
                            //  STORE_ID ,VISIT_DATE ,BREAKNAME ,BREAKID ,STARTTIME ,ENDTIME ,MAXNUMBER ,MINNUMBER ,ADDED_DATE 
                            // let {BreakName,BreakID,uniqueBreakId,StartTime,EndTime}=data;
                            let { STORE_ID, VISIT_DATE, BREAKNAME, BREAKID, STARTTIME, UNIQUEBREAKID, ENDTIME, MAXNUMBER, MINNUMBER, ADDED_DATE } = data
                            let newObj = { BreakName: BREAKNAME, BreakID: BREAKID, uniqueBreakId: UNIQUEBREAKID, StartTime: STARTTIME, EndTime: ENDTIME }

                            console.log("ENDTIME--fsd--------", ENDTIME)
                            if (ENDTIME == "" || ENDTIME == null || ENDTIME == undefined) {
                                let formData = AddVisFormData
                                formData["BreakName"] = BREAKNAME
                                formData["StartTime"] = STARTTIME
                                formData["uniqueBreakId"] = UNIQUEBREAKID

                                BgAddVisFormData(formData)
                                props.set_AllKPIDisable(true)
                                BgUnsavedChanges(true)
                                setrerenderdata(!rerenderdata);
                            }

                            arr.push(newObj);
                            console.log("BREAKTIME-------", arr)
                            if (i == txnres2.rows.length - 1) { setReportData(arr); setProcessing(false); }

                        }
                    }
                    setProcessing(false)
                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); },);

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


    function cancelImage() {
        // setImage1('');
        setSelectedImg('');
        setReCapImgModalObj({})
        setShowModal(false);
    }

    async function getImage(imgdata) {
        if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
            notify(ST.Cameraunavailable);
        }
        else if (typeof imgdata == 'object' && imgdata.uri != null) {
            const img = imgdata;
            const imgurl = img.uri, imgWidth = img.width, imgHeight = img.ExtendedHeight;
            let isImgFromGallery = img.fromGallery != null ? img.fromGallery : false;
            let picture_clickedd = isImgFromGallery == true ? img.datetime : new Date();
            ////change by jeevanp
            let picture_clicked_time = moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name = moment(picture_clickedd).format('MMDDYYYY_HHmmss')

            console.log("time", picture_clicked_time);
            console.log("time1", picture_clicked_time_for_pic_name);
            ////change by jeevanp
            let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
            let calculate_tym_date_over_img = picture_clicked_time;

            let filename = storeData.StoreId + '_' + (props.UserId || '') + '_BreakTimeImg-' + calculate_tym_date_for_filename + '.jpg';
            console.log(filename, "file_name");

            const mark_text1 = calculate_tym_date_over_img;
            const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: Break Time ' + ' | Date:' + calculate_tym_date_over_img;
            console.log(mark_text1 + "\n" + mark_text2, "mark_text2");


            let addvisdata = AddVisFormData;
            let image_key = 'Image1';
            let image_path_key = 'Image1Path';
            addvisdata[image_key] = filename;


            let imagePath = `${ImageFolderPath + currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
                .then(async (resn) => {
                    // render data with clicked image
                    let uri = 'file://' + imagePath;
                    addvisdata[image_path_key] = uri;

                    setSelectedImg(uri)
                    BgAddVisFormData(addvisdata)
                    BgUnsavedChanges(true)
                    setrerenderdata2(!rerenderdata2);
                    // add metdata then resize image and restored back to the imagePath
                    let restore_data = { "destFilePath": imagePath, "imgurl": imgurl, imgWidth, imgHeight, mark_text1, mark_text2 }
                    let is_restored = await restore_ImageWithMetaData(restore_data, imgdata);
                    console.log("image restored:", is_restored);
                })
                .catch(err => {
                    console.log('ERROR: image file write failed!!!');
                    console.log(err.message, err.code);
                });                

        }
    }


    async function openCamera(type = '1') {
        console.log('openCamera');
        setClickImageType(type);
        setShowCamera(true);
    }

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

    async function saveData(formData, type = "StartTime") {
        // setHasUnsavedChanges(false);
        BgUnsavedChanges(false)
        setShowAlert(false);
        // setProcessing(true);
        try {
            console.log("formData----------", formData)
            let { StoreId } = storeData;
            await db.transaction(async function (txn) {
                // STORE_ID ,VISIT_DATE ,BREAKNAME ,BREAKID ,STARTTIME ,ENDTIME ,MAXNUMBER ,MINNUMBER ,ADDED_DATE 
                let { BreakName, BreakID, uniqueBreakId, StartTime, EndTime } = formData;
                var values = '', add_data = '';

                // MAXNUMBER ,MINNUMBER
                let isFromDateIndex = BreakTypes.findIndex(i => i.BreakID == BreakID);
                let isFromDateKPIObj = isFromDateIndex >= 0 ? BreakTypes[isFromDateIndex] : {};
                let MaxCount = isFromDateIndex >= 0 ? isFromDateKPIObj['MinNumber'] : 0;
                let MinCount = isFromDateIndex >= 0 ? isFromDateKPIObj['MaxNumber'] : 0;
                console.log("isFromDateKPIObj----------------", isFromDateKPIObj)

                if (type == 'StartTime') {
                    values = ` ('${StoreId}','${uniqueBreakId}','${d2}','${BreakName}','${BreakID}','${StartTime}','${d2}','${MaxCount}','${MinCount}') `;
                    add_data = `INSERT INTO ${AppTables.BREAKTIME} (STORE_ID ,UNIQUEBREAKID,VISIT_DATE ,BREAKNAME ,BREAKID ,STARTTIME ,ADDED_DATE,MAXNUMBER ,MINNUMBER ) VALUES ${values} `;
                } else if (type == 'EndTime') {
                    add_data = `UPDATE ${AppTables.BREAKTIME} SET ENDTIME='${EndTime}'  WHERE  STORE_ID='${StoreId}' and UNIQUEBREAKID='${uniqueBreakId}' and VISIT_DATE='${d2}'`
                }

                console.log("add_data-----------sda", add_data)
                await txn.executeSql(add_data, [], async function (txn2, txnres) {
                    console.log('av added');
                    notify("added successfully", 'SHORT');
                    // clear store data in local storage to avoiding re-set data for the store  
                    clear_item('storeData')

                }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); notify("Cannot add Time") },);

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


    async function DisableCon(label) {

        let isValid = true;
        // for(var i=0;i<BreakTypes.length;i++){
        //     let item = BreakTypes[i]
        let isFromDateIndex = BreakTypes.findIndex(i => i.BreakName == label);
        let isFromDateKPIObj = isFromDateIndex >= 0 ? BreakTypes[isFromDateIndex] : {};
        let MaxCount = isFromDateIndex >= 0 ? isFromDateKPIObj['MaxNumber'] : 0;
        let item = label

        let count = 0
        for (var i = 0; i < reportData.length; i++) {
            let recordItem = reportData[i]
            if (label == recordItem.BreakName) {
                count++
            }
        }
        console.log("MaxCount<=count--------", MaxCount, "<=", count, MaxCount < count)
        if (MaxCount <= count) {
            isValid = false;
            notify(ST.Pleaseaddfirst, 'SHORT');
        }
        // }
        console.log('isValid:', isValid);
        setIsDisable(isValid)
        setrerenderdata(!rerenderdata);
        return isValid;
    }


    async function validate() {

        let isValid = true;

        if (isAddVisPresent == 1 && AddVisibility.length <= 0) {
            isValid = false;
            notify(ST.Pleaseaddfirst, 'SHORT');
        }


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

    async function validateForm() {
        let isValid = true;
        let { CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, Remark, Image1, Image1Path, FromDate, ToDate, showFromDateFlag } = AddVisFormData;

        let isFromDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
        let isFromDateKPIObj = isFromDateIndex >= 0 ? KPIFields[isFromDateIndex] : {};
        let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;

        let isToDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowToDate');
        let isToDateKPIObj = isToDateIndex >= 0 ? KPIFields[isToDateIndex] : {};
        let isToDateEnable = isToDateIndex >= 0 ? isToDateKPIObj['KPIFieldEnable'] : true;


        if ((CategoryName == '' || CategoryName == null) || (CategoryId == '' || CategoryId == null)) {
            isValid = false;
            notify(ST.PleaseSelectCategory, 'SHORT');
        }
        else if ((SubCategoryName == '' || SubCategoryName == null) || (SubCategoryId == '' || SubCategoryId == null)) {
            isValid = false;
            notify(ST.Pleaseselectsubcategory, 'SHORT');
        }
        else if ((BrandName == '' || BrandName == null) || (BrandId == '' || BrandId == null)) {
            isValid = false;
            notify(ST.Pleaseselectbrand, 'SHORT');
        }
        else if ((DisplayName == '' || DisplayName == null) || (DisplayId == '' || DisplayId == null)) {
            isValid = false;
            notify(ST.Pleaseselectdisplaytype, 'SHORT');
        }
        // else if((Remark=='' || Remark==null )){
        //     isValid=false;
        //     notify('Please enter remark','SHORT');
        // }
        else if (isFromDateEnable == true &&
            !AddVisFormData.hasOwnProperty("FromDate") &&
            (FromDate == '' || FromDate == null)) {
            isValid = false;
            notify('Please Select The From Date ', 'SHORT');
        } else if (isToDateEnable == true &&
            !AddVisFormData.hasOwnProperty("ToDate") &&
            (ToDate == '' || ToDate == null)) {
            isValid = false;
            notify('Please Select The To Date ', 'SHORT');
        }
        else if (StoreCameraAllow == true && (Image1 == '' || Image1 == null)) {
            isValid = false;
            notify(ST.Pleaseclickimage, 'SHORT');
        }

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

    function onConfirmRemoveAll() {
        // Remove all data 
        if (animatedChoice != null) {
            Animated.timing(animatedChoice, {
                toValue: 0,
                duration: 400,
                useNativeDriver: false,
            }).start();
        }
        // setIsAddVisPresent(0);
        // setHasUnsavedChanges(true);
        // setAddVisibility([]);
        // setAddVisFormData({});
        BgIsAddVisPresent(0);
        BgUnsavedChanges(true)
        BgWindowData([])
        BgAddVisFormData({})
        setShowRAllC_M(false);
    }

    function onSaveCancel() {
        setShowAlert(false);
    }

    function onselectionChange(option, keyLbl, keyVal, otherData) {
        let data = AddVisFormData;
        data[keyVal] = option.value;
        data[keyLbl] = option.label;
        console.log("option,keyLbl,keyVal--", option, keyLbl, keyVal, otherData)
        DisableCon(option.label)
        // CleanSelector(option,keyLbl, data)

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

    }

    async function StartBreakAdd() {

        let arr = reportData;
        let formData = AddVisFormData
        let uniqueBreakId = "_Break" + moment(new Date()).format('DDMMYYYYHHmmss')
        let picture_clicked_STamp = moment(new Date()).format('HH:mm:ss');
        formData["StartTime"] = picture_clicked_STamp
        formData["uniqueBreakId"] = uniqueBreakId

        // setShowRAllC_M(true);
        arr.push(formData);

        set_item('AllKPIDisable', "true");
        setReportData(arr)
        BgAddVisFormData(formData)
        saveData(formData, "StartTime")
        BgWindowData(arr)
        props.set_AllKPIDisable(true)
        BgUnsavedChanges(true)
        notify("Start Time added successfully", 'LONG');
        setrerenderdata(!rerenderdata);

    }

    async function EndBreakAdd() {

        let arr = reportData;
        let formData = AddVisFormData


        // let isBreakIndex=arr.findIndex(i=>i.BreakID==formData.BreakID)
        let isBreakIndex = arr.length - 1
        let isBreakIndexObj = isBreakIndex >= 0 ? arr[isBreakIndex] : {};

        let picture_clicked_STamp = moment(new Date()).format('HH:mm:ss');
        isBreakIndexObj["EndTime"] = picture_clicked_STamp;
        formData[isBreakIndex] = isBreakIndexObj;
        arr[isBreakIndex] = isBreakIndexObj

        clear_item('AllKPIDisable');
        props.set_AllKPIDisable(false)
        setReportData(arr)
        saveData(isBreakIndexObj, "EndTime")
        BgWindowData(arr)
        BgAddVisFormData({})
        BgUnsavedChanges(true)

        notify("End Time added successfully", 'LONG');
        setrerenderdata(!rerenderdata);

    }

    async function Add_AddVis() {
        let isValid = await validateForm();
        console.log('isValid add:', isValid);
        if (isValid) {
            let arr = AddVisibility;
            let { CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, Remark, Image1, Image1Path } = AddVisFormData;

            // let index=AddVisibility.findIndex(i=>i.CategoryId==CategoryId && i.SubCategoryId==SubCategoryId && i.BrandId==BrandId && i.DisplayId==DisplayId);
            // if(index>=0){
            //     notify(ST.Thisvisibilityhasalreadybeenadded,'LONG');
            // }
            // else{
            arr.push(AddVisFormData);
            // setAddVisibility(arr);
            // setHasUnsavedChanges(true);
            BgWindowData(arr)
            BgUnsavedChanges(true)
            notify(ST.AdditionalVisibilityaddedsuccessfully, 'LONG');
            setrerenderdata(!rerenderdata);

            // clear data
            setFromDate('');
            BgAddVisFormData({})
            setToDate('');
            // setAddVisFormData({});
            // }
        }

    }

    function showRemoveConfirm(item, index) {
        setToRemoveId(index);
        setToRemoveItem(item);
        setshowRemoveConfirm_M(true);
    }

    function Remove_AddVis() {
        let index = toRemoveId
        let item = toRemoveItem;
        let arr = AddVisibility;
        console.log('toRemoveId:', index);
        if (index >= 0 && index < arr.length) {
            arr.splice(index, 1);
            // setAddVisibility(AddVisibility);
            // setHasUnsavedChanges(true);
            BgWindowData(AddVisibility)
            BgUnsavedChanges(true)
            notify(ST.Visibilityremovedsuccessfully, 'LONG')
            setrerenderdata(!rerenderdata);
        }
        else {
            notify(ST.CannotremoveVisibilitynotfound, 'LONG')
        }
        setToRemoveId('');
        setToRemoveItem({});
        setshowRemoveConfirm_M(false);

    }

    function _OpenCaptureImage_Modal(img) {

        const isImageCap = (img != '' || img != null) ? true : false;
        // console.log("imag pop is trigger",isImageCap,showModal,img)
        let { window, splitItem, splitItemIndex, cameraType } = reCapImgModalObj
        let camera2Label = (window && window.PromoImage2Lable) || '';
        return (
            <CustomModal
                style={customStyle.PromoImgModal}
                title={"Break Time Rules"}
                message={camera2Label}
                titleStyle={customStyle.PromoImgModal_title}
                messageStyle={customStyle.PromoImgModal_subtitle}
                showModal={showModal}
            >
                {
                    <View style={customStyle.Break_ConWrap}>
                        <View style={customStyle.StSC_RTblHeader}>
                            <View style={[customStyle.StSC_RTblHeaderBox, customStyle.BreakI_RTblHeaderBox1]}>
                                <Text style={[customStyle.Break_RTblHeaderTxt]}>{"Break Type"}</Text>
                            </View>
                            <View style={[customStyle.StSC_RTblHeaderBox, customStyle.BreakI_RTblHeaderBox2]}>
                                <Text style={customStyle.Break_RTblHeaderTxt}>{'Min Count'}</Text>
                            </View>
                            <View style={[customStyle.StSC_RTblHeaderBox, customStyle.BreakI_RTblHeaderBox3]}>
                                <Text style={customStyle.Break_RTblHeaderTxt}>{'Max Count'}</Text>
                            </View>
                        </View>
                        <View style={[customStyle.StSCreportCon, { marginLeft: 10, marginBottom: 10 }]}>
                            <View style={[customStyle.StSC_RTblBody]}>
                                {
                                    BreakTypes.length > 0 &&
                                    BreakTypes.map((item, index) => {

                                        let colorCode = item ? (item.Score == 5 ? "#FFBF00" : item.Score == 0 ? "#ff0000" : item.Score == 10 ? "#32CD32" : "") : ""
                                        return (
                                            <View style={[customStyle.StSC_RItem, (index != BreakTypes.length - 1 ? customStyle.StSC_RtemB : {})]} key={index}>
                                                <View style={[customStyle.StSC_RItemCol, customStyle.BreakI_RItemCol1]}>
                                                    <Text style={[customStyle.StSC_RItemColText, { paddingVertical: 10 }]}>{item.BreakName}</Text>
                                                </View>
                                                <View style={[customStyle.StSC_RItemCol, customStyle.BreakI_RItemCol2]}>
                                                    <Text style={[customStyle.StSC_RItemColText, { paddingVertical: 10 }]}>{item.MinNumber}</Text>
                                                </View>
                                                <View style={[customStyle.StSC_RItemCol, customStyle.BreakI_RItemCol3, { backgroundColor: colorCode }]}>
                                                    <Text style={[customStyle.StSC_RItemColText, { paddingVertical: 10 }]}>{item.MaxNumber}</Text>
                                                </View>
                                            </View>
                                        )
                                    })
                                }
                            </View>
                        </View>

                        <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={() => { setShowModal(false) }}>
                            <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                        </TouchableOpacity>

                    </View>
                }
            </CustomModal>
        )
    }



    function _render_addVisFormTop() {
        let xpos = 0;
        if (animatedChoice != null) {
            xpos = animatedChoice.interpolate({
                inputRange: [0, 1],
                outputRange: [0, -75],
            });
        }

        let isFromDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowFromDate');
        let isFromDateKPIObj = isFromDateIndex >= 0 ? KPIFields[isFromDateIndex] : {};
        let isFromDateEnable = isFromDateIndex >= 0 ? isFromDateKPIObj['KPIFieldEnable'] : true;

        let isToDateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'ShowToDate');
        let isToDateKPIObj = isToDateIndex >= 0 ? KPIFields[isToDateIndex] : {};
        let isToDateEnable = isToDateIndex >= 0 ? isToDateKPIObj['KPIFieldEnable'] : true;

        // && (AddVisFormData.EndTime==undefined || AddVisFormData.EndTime=='')

        let startDis = (AddVisFormData.BreakName != undefined && AddVisFormData.BreakName != '')
        let startDis1 = IsDisable == true ? (startDis ? ((AddVisFormData.StartTime != undefined && AddVisFormData.StartTime != '') ? false : true) : false) : false

        console.log("AddVisFormData.StartTime=", AddVisFormData.StartTime != undefined && AddVisFormData.StartTime, AddVisFormData.StartTime)
        // storeData
        return (

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

                <View style={customStyle.BreakclocktimerWrap}>

                    <View style={customStyle.BreakclocktimerRow}>
                        <Text style={[customStyle.BreakclocktimerText, { color: "#000" }]}>{"Login Time - " + storeData.CheckInTime}</Text>
                    </View>

                    <View style={{ paddingLeft: "15%", paddingRight: 0, marginBottom: "10%" }}>
                        <TouchableOpacity onPress={() => { setShowModal(true) }}>
                            <Feather name='info' color={PageTheme.$primary_color} size={18} />
                        </TouchableOpacity>
                    </View>
                </View>

                <View style={[customStyle.StSCreportCon, { margin: 2, marginBottom: 10 }]}>
                    <View style={[customStyle.StSC_RTblBody]}>

                        <View style={customStyle.BreakaddVisForm}>
                            <View style={customStyle.BreakaddVisRow}>
                                <View style={[customStyle.BreakaddVisCol50, customStyle.BreakaddVisCol1]}>
                                    {CustomPicker(props, BreakTypes, 'BreakName', 'BreakID', 'BreakName', 'BreakID', onselectionChange, { value: AddVisFormData.BreakName, })}
                                </View>
                            </View>
                        </View>
                        <View style={[customStyle.addvis_pCon]}>
                            <View style={{ flexDirection: "column" }}>
                                {
                                    AddVisFormData &&
                                    AddVisFormData.StartTime != "" && AddVisFormData.StartTime != undefined && <Text style={customStyle.Break_VisLabel}>{"Start Time-" + AddVisFormData.StartTime}</Text>
                                }

                                <TouchableOpacity style={[customStyle.Break_Vis_btn, { backgroundColor: (startDis1 ? PageTheme.$primary_color : "#E1E3E2") }]} onPress={() => { startDis1 ? StartBreakAdd() : null }}>
                                    <Text style={[customStyle.Break_VisBtnText, { color: (startDis1 ? PageTheme.$accent_color : "#000") }]}>{"START"}</Text>
                                </TouchableOpacity>
                            </View>
                            <View style={[customStyle.addvis_pChoiceBoxCon, { marginLeft: 20 }]}>
                                <View style={{ flexDirection: "column" }}>
                                    {
                                        AddVisFormData &&
                                        AddVisFormData.StartTime != "" && AddVisFormData.StartTime != undefined && <Text style={customStyle.Break_VisLabel}>{""}</Text>
                                    }
                                    <TouchableOpacity style={[customStyle.Break_Vis_btn, { backgroundColor: (AddVisFormData.StartTime != undefined && AddVisFormData.StartTime != '' ? PageTheme.$primary_color : "#E1E3E2") }]} onPress={() => { AddVisFormData.StartTime != undefined && AddVisFormData.StartTime != '' ? EndBreakAdd() : null }}>
                                        <Text style={[customStyle.Break_VisBtnText, { color: (AddVisFormData.StartTime != undefined && AddVisFormData.StartTime != '' ? PageTheme.$accent_color : "#000") }]}>{"END"}</Text>
                                    </TouchableOpacity>

                                </View>
                            </View>
                        </View>
                    </View>
                </View>
                {
                    <View style={customStyle.StSC_ConWrap}>
                        <View style={customStyle.StSC_RTblHeader}>
                            <View style={[customStyle.StSC_RTblHeaderBox, customStyle.Break_RTblHeaderBox1]}>
                                <Text style={[customStyle.Break_RTblHeaderTxt]}>{"Break Type"}</Text>
                            </View>
                            <View style={[customStyle.StSC_RTblHeaderBox, customStyle.Break_RTblHeaderBox2]}>
                                <Text style={customStyle.Break_RTblHeaderTxt}>{'Start Time'}</Text>
                            </View>
                            <View style={[customStyle.StSC_RTblHeaderBox, customStyle.Break_RTblHeaderBox3]}>
                                <Text style={customStyle.Break_RTblHeaderTxt}>{'End Time'}</Text>
                            </View>
                            <View style={[customStyle.StSC_RTblHeaderBox, customStyle.Break_RTblHeaderBox3]}>
                                <Text style={customStyle.Break_RTblHeaderTxt}>{'Duration'}</Text>
                            </View>
                        </View>
                        <ScrollView
                            contentContainerStyle={customStyle.StSC_scrollViewInner}
                            style={customStyle.StSC_scrollView}
                        >
                            <View style={customStyle.StSCreportCon}>
                                <View style={[customStyle.StSC_RTblBody]}>
                                    {
                                        reportData.length > 0 &&
                                        reportData.map((item, index) => {

                                            let colorCode = item ? (item.Score == 5 ? "#FFBF00" : item.Score == 0 ? "#ff0000" : item.Score == 10 ? "#32CD32" : "") : ""

                                            var startTime = item.StartTime != null && item.StartTime1 != "" ? moment(item.StartTime, 'HH:mm:ss') : "";
                                            var endTime = item.EndTime != null && item.EndTime1 != "" ? moment(item.EndTime, 'HH:mm:ss') : "";

                                            var duration = startTime != '' && endTime != "" ? moment.utc(moment(endTime, "HH:mm:ss").diff(moment(startTime, "HH:mm:ss"))).format("HH:mm:ss") : ""
                                            console.log("duration-------", duration)
                                            return (
                                                <View style={[customStyle.StSC_RItem, ((index < (reportData.length - 1)) ? customStyle.StSC_RtemB : {})]} key={index}>
                                                    <View style={[customStyle.StSC_RItemCol, customStyle.Break_RItemCol1]}>
                                                        <Text style={[customStyle.StSC_RItemColText, { paddingVertical: 10 }]}>{item.BreakName}</Text>
                                                    </View>
                                                    <View style={[customStyle.StSC_RItemCol, customStyle.Break_RItemCol2]}>
                                                        <Text style={[customStyle.StSC_RItemColText, { paddingVertical: 10 }]}>{item.StartTime}</Text>
                                                    </View>
                                                    <View style={[customStyle.StSC_RItemCol, customStyle.Break_RItemCol3, { backgroundColor: colorCode }]}>
                                                        <Text style={[customStyle.StSC_RItemColText, { paddingVertical: 11 }]}>{item.EndTime}</Text>
                                                    </View>
                                                    <View style={[customStyle.StSC_RItemCol, customStyle.Break_RItemCol3, { backgroundColor: colorCode }]}>
                                                        <Text style={[customStyle.StSC_RItemColText, { paddingVertical: 11 }]}>{duration}</Text>
                                                    </View>
                                                </View>
                                            )
                                        })
                                    }

                                </View>
                            </View>
                        </ScrollView>

                    </View>
                }
                {
                    (rerenderdata == rerenderdata) &&
                    <ScrollView contentContainerStyle={customStyle.addVisScrollCon} style={customStyle.addVisScroll}>
                        <View style={customStyle.addVisForm}>
                            <View style={customStyle.addVisRow}>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{ST.Category}</Text>
                                        {CustomPicker(props, Categories, 'CategoryName', 'CategoryId', 'CategoryName', 'CategoryId', onselectionChange, { value: AddVisFormData.CategoryName })}

                                    </View>
                                </View>
                                <View style={[customStyle.addVisCol50, customStyle.addVisCol2]}>
                                    <View style={customStyle.addVisFormGrp}>
                                        <Text style={customStyle.addVisLabel}>{'Sub Category'}</Text>

                                        {CustomPicker(props, SubCategories, 'SubCategoryName', 'SubCategoryId', 'SubCategoryName', 'SubCategoryId', onselectionChange, { value: AddVisFormData.SubCategoryName })}
                                    </View>
                                </View>

                                <View style={customStyle.addVis_btnWrap}>
                                    <TouchableOpacity style={customStyle.addVis_btn} onPress={() => { Add_AddVis() }}>
                                        <Text style={customStyle.addVisBtnText}>{ST.Add}</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>

                    </ScrollView>
                }
            </View>
        )
    }

    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            {_OpenCaptureImage_Modal()}
            {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
            {ConfirmSaveAlert(props, showRemoveConfirm_M, () => { setshowRemoveConfirm_M(false) }, Remove_AddVis, ST.Doyoureallywanttoremovethisvisibility)}
            {ConfirmSaveAlert(props, showRAllC_M, () => { setShowRAllC_M(false) }, onConfirmRemoveAll, ST.Doyoureallywanttoremoveallvisibilitydata)}
            <CustomCamera cameraType={'back'} BottomText={'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: ' + currentMenu.MenuName} 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, customStyle.zIndex0]}>
                <View style={[customStyle.pageContentWrapper]}>
                    {Object.keys(storeData).length > 0 &&
                        <View style={customStyle.addVis_Wrapper}>
                            {_render_addVisFormTop()}
                        </View>
                    }
                    {/* <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{onSubmitData()}}/> 
            </View>   */}
                </View>

            </LinearGradient>

        </Container>
    );
}



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