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 } 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, marktext1, marktext2 } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr, common_ImagePath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { Card, Menu, Switch } from 'react-native-paper';
import { AntDesign, Entypo, FontAwesome, 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 { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector'
import { CustomPicker } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';

function CompetitionVisibility(props) {
  const route = useRoute();

  // 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('loading...');
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [storeData, setStoreData] = useState({});
  const [currentMenu, setCurrentMenu] = useState({});
  const [brandData, setBrandData] = useState([]);
  const [rerenderdata, setrerenderdata] = useState(0);
  const [rerenderdata2, setrerenderdata2] = useState(0);

  const [AddVisibility, setAddVisibility] = useState([]);
  const [AddVisFormData, setAddVisFormData] = useState({});
  const [isAddVisPresent, setIsAddVisPresent] = useState(0);
  const [showAlert, setShowAlert] = useState(false);
  const [Companies, setCompanies] = useState([]);
  const [Categories, setCategories] = useState([]);
  const [SubCategories, setSubCategories] = useState([]);
  const [Brands, setBrands] = useState([]);
  const [DisplayList, setDisplayList] = useState([]);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [showCamera, setShowCamera] = useState(false);
  const [getImageProps, setGetImageProps] = useState({});
  const [toRemoveId, setToRemoveId] = useState('');
  const [toRemoveItem, setToRemoveItem] = useState({});
  const [showRemoveConfirm_M, setshowRemoveConfirm_M] = useState(false);
  const [showRAllC_M, setShowRAllC_M] = useState(false);
  const [EmpData, setEmpData] = useState([]);


  const d1 = new Date();
  const d2 = moment(d1).format('MM/DD/YYYY');


  useEffect(() => {
    let params = props.route.params ? props.route.params : {};
    let storeData1 = params.storeData || {};
    let menu1 = params.menu || {};
    let empData1 = params.empData || {};

    let isAdhoc = params.isAdhoc || false;
    setIsAdhocScreen(isAdhoc);
    setStoreData(storeData1);
    setEmpData(empData1);
    setCurrentMenu(menu1);

    getData(storeData1);

    const onremoveSubscription = props.navigation.addListener('beforeRemove', onBeforeRemove);

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

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

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

  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) {
    { setHasUnsavedChanges(false); props.navigation.dispatch(e.data.action); }
    // Alert.alert(
    //     "",
    //     "Do you really want to exit the screen?",
    //     [
    //       {
    //         text: "Cancel",
    //         onPress: () => {},
    //         style: "cancel"
    //       },
    //       { text: "OK", onPress: () => {setHasUnsavedChanges(false);props.navigation.dispatch(e.data.action);} }
    //     ]
    //   );
  }


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


      db.transaction(async function (txn) {

        let q4 = `Select distinct CategoryId,CategoryName from Sup_Product_Master where IsCompetitor ='1'`;
        await txn.executeSql(q4, [], 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);
              arr.push(data);
              if (i == txnres2.rows.length - 1) { setCategories(arr); }
            }
          }
        }, function (txn2, txnerr) { console.log(txnerr); },);

        let q2 = `Select Distinct DisplayId,DisplayName from Sup_Master_Display`;
        await txn.executeSql(q2, [], 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);
              arr.push(data);
              if (i == txnres2.rows.length - 1) { setDisplayList(arr); }
            }
          }
        }, function (txn2, txnerr) { console.log(txnerr); },);


        let q3 = `Select * from ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' and VISIT_DATE='${d2}'  `;
        await txn.executeSql(q3, [], 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 { PRESENT, CATEGORY, CATEGORY_ID, SUB_CATEGORY, SUB_CATEGORY_ID, BRAND, BRAND_ID, DISPLAY, DISPLAY_ID, REMARK, IMAGE } = data;
              let datan = { CategoryName: CATEGORY, CategoryId: CATEGORY_ID, SubCategoryName: SUB_CATEGORY, SubCategoryId: SUB_CATEGORY_ID, BrandName: BRAND, BrandId: BRAND_ID, DisplayName: DISPLAY, DisplayId: DISPLAY_ID, Remark: REMARK, Image1: IMAGE }
              // datan.Image1Path=common_ImagePath+IMAGE;
              datan.Image1Path = 'file://' + common_ImagePath + IMAGE;
              PRESENT == 1 ? arr.push(datan) : '';
              let isPresent = PRESENT;
              if (i == txnres2.rows.length - 1) {
                Animated.timing(animatedChoice, {
                  toValue: isPresent,
                  duration: 400,
                  useNativeDriver: false,
                }).start();
                setAddVisibility(arr);
                setIsAddVisPresent(isPresent);

              }
            }
          }
        }, function (txn2, txnerr) { console.log(txnerr); },);

        setProcessing(false);

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



  async function getImage(imgdata) {
    let type = getImageProps.type || '';
    if (typeof imgdata == 'object' && imgdata.errorCode == 'camera_unavailable') {
      notify('Camera unavailable');
    }
    else if (typeof imgdata == 'object' && imgdata.uri != null) {
      const img = imgdata;
      const imgurl = img.uri, imgWidth = img.width, imgHeight = img.height;


      let picture_clicked_time = new Date();
      picture_clicked_time = moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')


      const mark_text1 = picture_clicked_time;
      const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: Comp. Visibility' + ' | Date:' + picture_clicked_time;

      await marktext1(mark_text1, imgurl)
        .then((res) => {
          if (res.success) {
            let uri = res.uri;
            marktext2(mark_text2, uri, imgWidth, imgHeight)
              .then((res) => {
                if (res.success) {
                  let picture_clickedd = new Date();
                  let picture_clicked_date = moment(picture_clickedd).format('YYYYMMDD');
                  let picture_clicked_time = moment(picture_clickedd).format('HHmmss');
                  let filename = storeData.StoreId + '_' + (props.UserId || '') + '_CompVisibilityImg-' + picture_clicked_date + '_' + picture_clicked_time + '.jpg';


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

                  // renamefile
                  let imagePath = `${common_ImagePath}/${filename}`;
                  RNFS.copyFile(res.uri, imagePath)
                    .then(resn => {
                      let uri = 'file://' + imagePath;
                      console.log('image marker', uri);
                      addvisdata[image_path_key] = uri;

                      setAddVisFormData(addvisdata);
                      setHasUnsavedChanges(true);
                      setrerenderdata2(!rerenderdata2);
                    })
                    .catch(err => {
                      console.log('ERROR: image file write failed!!!');
                      console.log(err.message, err.code);
                    });

                }
                else {
                  if (res.imagenotfound) {
                    notify('Please capture a image');
                  }
                  else {
                    notify(res.error);
                  }
                }
              });
          }
          else {
            if (res.imagenotfound) {
              notify('Please capture a image');
            }
            else {
              notify(res.error);
            }
          }
        });
    }
  }

  async function openCamera(type = '1') {
    setGetImageProps({ 'type': type });
    setShowCamera(true);
    // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'back'})
  }

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

  async function saveData() {
    setHasUnsavedChanges(false);
    setShowAlert(false);
    setLoaderTitle('Saving Data...');
    setProcessing(true);
    try {
      let { StoreId, ChainId, StateId, StoreTypeId } = storeData;
      await db.transaction(async function (txn) {

        let q = `DELETE FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${StoreId}' and EMP_ID='${storeData.MerchandiserId}' and VISIT_DATE='${d2}' `;

        //  remove old data
        await txn.executeSql(q, [], async function (txn2, txnres) {
          console.log('cv data deleted');
        }, function (txn2, txnerr) { console.log(txnerr); },);

        var values = '';
        if (isAddVisPresent == 1 && AddVisibility.length > 0) {
          for (var i = 0; i < AddVisibility.length; i++) {
            let catIndex = i;
            let item = AddVisibility[catIndex];
            let { CategoryName, CategoryId, SubCategoryName, SubCategoryId, BrandName, BrandId, DisplayName, DisplayId, Remark, Image1, Image1Path } = item;
            values += values != '' ? ' , ' : '';
            values += ` ('${storeData.MerchandiserId}','${StoreId}','${d2}','${isAddVisPresent}','${CategoryName}','${CategoryId}','${SubCategoryName}','${SubCategoryId}','${BrandName}','${BrandId}','${DisplayName}','${DisplayId}','${Remark}','${Image1}','${d2}') `;

          }
        }
        else {
          values += `('${storeData.MerchandiserId}','${StoreId}','${d2}','${isAddVisPresent}','','','','','','','','','','','${d2}')`;
        }

        console.log('values:', values);
        let add_data = `INSERT INTO ${AppTables.COMPETITION_VISIBILITY} (EMP_ID,STORE_ID,VISIT_DATE,PRESENT,CATEGORY,CATEGORY_ID,SUB_CATEGORY,SUB_CATEGORY_ID,BRAND,BRAND_ID,DISPLAY,DISPLAY_ID,REMARK,IMAGE,ADDED_DATE) VALUES ${values} `;

        await txn.executeSql(add_data, [], async function (txn2, txnres) {
          console.log('av added');
          notify('Competition Visibility added successfully', 'SHORT');
          setProcessing(false);
          props.navigation.goBack();
        }, function (txn2, txnerr) { console.log(txnerr); setProcessing(false); notify('Cannot add competition visibility') },);


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




  async function validate() {

    let isValid = true;
    if (isAddVisPresent == 1 && AddVisibility.length <= 0) {
      isValid = false;
      notify('Please add first', '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 } = AddVisFormData;

    if ((CategoryName == '' || CategoryName == null) || (CategoryId == '' || CategoryId == null)) {
      isValid = false;
      notify('Please select category', 'SHORT');
    }
    else if ((SubCategoryName == '' || SubCategoryName == null) || (SubCategoryId == '' || SubCategoryId == null)) {
      isValid = false;
      notify('Please select sub category', 'SHORT');
    }
    else if ((BrandName == '' || BrandName == null) || (BrandId == '' || BrandId == null)) {
      isValid = false;
      notify('Please select brand', 'SHORT');
    }
    else if ((DisplayName == '' || DisplayName == null) || (DisplayId == '' || DisplayId == null)) {
      isValid = false;
      notify('Please select display type', 'SHORT');
    }
    else if ((Remark == '' || Remark == null)) {
      isValid = false;
      notify('Please enter remark', 'SHORT');
    }
    else if ((Image1 == '' || Image1 == null)) {
      isValid = false;
      notify('Please click image', 'SHORT');
    }


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

  function onFormDataChange(val, key) {
    let data = AddVisFormData;
    data[key] = val;
    setAddVisFormData(data);
    setHasUnsavedChanges(true);
    setrerenderdata(!rerenderdata);
  }

  function onselectionChange(option, keyLbl, keyVal, otherData) {

    let data = AddVisFormData;
    data[keyVal] = option.value;
    data[keyLbl] = option.label;

    setHasUnsavedChanges(true);

    if (keyLbl == 'CategoryName') {
      loadData(option.value, 'SubCategories', '', '');

      data['SubCategoryId'] = '';
      data['SubCategoryName'] = '';
      data['BrandId'] = '';
      data['BrandName'] = '';
      data['DisplayId'] = '';
      data['DisplayName'] = '';


      
    }
    else if (keyLbl == 'SubCategoryName') {
      loadData(option.value, 'Brands');

      data['BrandId'] = '';
      data['BrandName'] = '';
    }

    setAddVisFormData(data);
    setrerenderdata(!rerenderdata);


  }

  async function loadData(qId, type) {
    try {
      await db.transaction(async function (txn) {
        let q = '';
        if (type == 'SubCategories') q = `Select Distinct p.SubCategoryId,p.SubCategoryName from Sup_Product_Master p where p.CategoryId='${qId}' and IsCompetitor ='1' order by p.SubCategorySequence`;
        else if (type == 'Brands') q = `Select Distinct p.BrandName,p.BrandId from Sup_Product_Master p Where p.SubCategoryId='${qId}' and p.CategoryId='${AddVisFormData['CategoryId']}' and IsCompetitor ='1' order by p.BrandSequence`;

        console.log("sub query------------------------------------->",q)
        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);
              arr.push(data);
              if (i == txnres2.rows.length - 1) {
                if (type == 'SubCategories') setSubCategories(arr);
                else if (type == 'Brands') setBrands(arr);
              }
            }
          }
        }, function (txn2, txnerr) { console.log(txnerr); },);

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



  function onChoiceSelect(val, key) {
    if (val == 0 && AddVisibility.length > 0) {
      setShowRAllC_M(true);
      return;
    }
    var val1 = val == 1 ? 1 : 0;
    if (animatedChoice != null) {
      Animated.timing(animatedChoice, {
        toValue: val1,
        duration: 400,
        useNativeDriver: false,
      }).start();
    }
    setIsAddVisPresent(val);
    setHasUnsavedChanges(true);
    if (val == 0) {
      setAddVisibility([]);
      setAddVisFormData({});
    }
  }

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

  function onSaveCancel() {
    setShowAlert(false);
  }

  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;
      console.log(AddVisFormData);
      // let index=AddVisibility.findIndex(i=> i.CategoryId==CategoryId && i.SubCategoryId==SubCategoryId && i.BrandId==BrandId && i.DisplayId==DisplayId);
      // if(index>=0){
      //     notify('This visibility has already been added','LONG');
      // }
      // else{
      arr.push(AddVisFormData);
      // setAddVisibility(arr);
      // setHasUnsavedChanges(true);
      notify('Visibility added successfully', 'LONG');
      setrerenderdata(!rerenderdata);

      // clear data
      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(arr);
      setHasUnsavedChanges(true);
      notify('Visibility removed successfully', 'LONG')
      setrerenderdata(!rerenderdata);
    }
    else {
      notify('Cannot remove! Visibility not found', 'LONG')
    }
    setToRemoveId('');
    setToRemoveItem({});
    setshowRemoveConfirm_M(false);
  }




  function _render_addVisFormTop() {
    let xpos = 0;
    if (animatedChoice != null) {
      xpos = animatedChoice.interpolate({
        inputRange: [0, 1],
        outputRange: [0, -75],
      });
    }
    return (
      <View style={[customStyle.addvisCon]}>
        <View style={[customStyle.addvis_pCon]}>
          <Text style={[customStyle.addvis_pText]}>{'Is Present'}</Text>
          <View style={customStyle.addvis_pChoiceBoxCon}>
            <View style={[customStyle.openStk_prd_choiceBox, customStyle.addvis_pChoiceBoxbg]}>
              <Animated.View style={[customStyle.openStkCh_absolutebg, customStyle.openStkCh_con_active, (isAddVisPresent == '1' ? customStyle.openStkCh_con_green : customStyle.openStkCh_con_red),
              {
                transform: [{
                  translateX: xpos
                }],
              }
              ]}></Animated.View>
              <TouchableOpacity style={customStyle.openStkCh_con1} onPress={() => { onChoiceSelect(1, 'isPresent') }}>
                <Text style={[customStyle.openStkCh_text, (isAddVisPresent == 1 ? customStyle.openStkCh_textactive : {})]}>Yes</Text>
              </TouchableOpacity>
              <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={() => { onChoiceSelect(0, 'isPresent') }}>
                <Text style={[customStyle.openStkCh_text, (isAddVisPresent == 0 ? customStyle.openStkCh_textactive : {})]}>No</Text>
              </TouchableOpacity>
            </View>
          </View>

        </View>
        {
          isAddVisPresent == 1 && (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}>Category</Text>
                    {CustomPicker(props, Categories, 'CategoryName', 'CategoryId', 'CategoryName', 'CategoryId', onselectionChange, { value: AddVisFormData.CategoryName, otherData: {} })}

                  </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, otherData: {} })}
                  </View>
                </View>
                <View style={[customStyle.addVisCol50, customStyle.addVisCol1]}>
                  <View style={customStyle.addVisFormGrp}>
                    <Text style={customStyle.addVisLabel}>Brands</Text>

                    {CustomPicker(props, Brands, 'BrandName', 'BrandId', 'BrandName', 'BrandId', onselectionChange, { value: AddVisFormData.BrandName })}
                  </View>
                </View>
                <View style={[customStyle.addVisCol50, customStyle.addVisCol2]}>
                  <View style={customStyle.addVisFormGrp}>
                    <Text style={customStyle.addVisLabel}>Display Type</Text>
                    {CustomPicker(props, DisplayList, 'DisplayName', 'DisplayId', 'DisplayName', 'DisplayId', onselectionChange, { value: AddVisFormData.DisplayName })}
                  </View>
                </View>
                <View style={[customStyle.addVisCol100]}>
                  <View style={customStyle.addVisFormGrp}>
                    <Text style={customStyle.addVisLabel}>Remark</Text>
                    <TextInput
                      style={customStyle.addVisInputStyle}
                      value={(AddVisFormData.Remark || '')}
                      onChangeText={(val) => { onFormDataChange(val, 'Remark'); }}
                      autoComplete='off'
                    />
                  </View>
                </View>
                <View style={[customStyle.addVisCol100]}>
                  <View style={customStyle.addVisFormGrp}>
                    <Text style={customStyle.addVisLabel}>Image</Text>
                    <View style={customStyle.addVisCameras}>
                      <View style={customStyle.openStkCameraCon}>
                        {(AddVisFormData.Image1Path == '' || AddVisFormData.Image1Path == null) &&
                          <TouchableOpacity style={[customStyle.osCat_action_openCam, customStyle.osCat_actn_margin]} onPress={() => { openCamera('1') }}>
                            <SvgXml width={80} height={80} xml={cameraImg} />
                          </TouchableOpacity>
                        }
                        {(AddVisFormData.Image1Path != '' && AddVisFormData.Image1Path != null) &&
                          <View style={customStyle.osCatImageView}>
                            <Image style={customStyle.osCatImage} source={{ uri: AddVisFormData.Image1Path }} />
                            <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={() => { openCamera('1') }}>
                              <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color} />
                            </TouchableOpacity>
                          </View>
                        }
                      </View>

                    </View>
                  </View>
                </View>
                <View style={customStyle.addVis_btnWrap}>
                  <TouchableOpacity style={customStyle.addVis_btn} onPress={() => { Add_AddVis() }}>
                    <Text style={customStyle.addVisBtnText}>Add</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
            <View style={customStyle.addVis_list}>
              <Text style={customStyle.addVis_listhdrText}>Added Visibilities</Text>
              <View style={customStyle.addVis_listInner}>
                {
                  AddVisibility.length > 0 &&
                  AddVisibility.map((item, index) => {
                    console.log(item);
                    return (
                      <View key={index} style={customStyle.addVis_listItem}>
                        <View style={customStyle.addVis_listI_row2}>
                          <View style={customStyle.addVis_listIcol1}>
                            <View style={customStyle.addVis_listI_row}>
                              <Text style={customStyle.addVis_listI_Label}>Category :</Text>
                              <Text style={customStyle.addVis_listI_Val}>{item.CategoryName}</Text>
                            </View>
                            <View style={customStyle.addVis_listI_row}>
                              <Text style={customStyle.addVis_listI_Label}>Sub Category :</Text>
                              <Text style={customStyle.addVis_listI_Val}>{item.SubCategoryName}</Text>
                            </View>
                            <View style={customStyle.addVis_listI_row}>
                              <Text style={customStyle.addVis_listI_Label}>Brand :</Text>
                              <Text style={customStyle.addVis_listI_Val}>{item.BrandName}</Text>
                            </View>
                            <View style={customStyle.addVis_listI_row}>
                              <Text style={customStyle.addVis_listI_Label}>Display Type :</Text>
                              <Text style={customStyle.addVis_listI_Val}>{item.DisplayName}</Text>
                            </View>
                            <View style={[customStyle.addVis_listI_row, customStyle.addVis_listI_lastrow]}>
                              <Text style={customStyle.addVis_listI_Label}>Remark :</Text>
                              <Text style={customStyle.addVis_listI_Val}>{item.Remark}</Text>
                            </View>
                          </View>
                          <View style={customStyle.addVis_listIcol2}>
                            {/* <View style={[customStyle.addVis_listI_row,customStyle.addVis_listI_lastrow]}> */}
                            <Text style={[customStyle.addVis_listI_Label2, customStyle.mb20]}>Image</Text>
                            {(item.Image1Path != null && item.Image1Path != '') && <Image style={customStyle.addVis_listI_Image} source={{ uri: item.Image1Path }} />}
                            {/* </View> */}
                          </View>
                          <TouchableOpacity style={customStyle.addVis_btnRemove} onPress={() => { showRemoveConfirm(item, index) }}>
                            <FontAwesome name='trash' size={20} color={'red'} />
                          </TouchableOpacity>
                        </View>


                      </View>
                    );
                  })
                }
              </View>
            </View>
          </ScrollView>
        }
      </View>
    )
  }

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      <CustomHeader {...props} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
      {ConfirmSaveAlert(props, showAlert, onSaveCancel, saveData)}
      {ConfirmSaveAlert(props, showRemoveConfirm_M, () => { setshowRemoveConfirm_M(false) }, Remove_AddVis, 'Do you really want to remove this visibility?')}
      {ConfirmSaveAlert(props, showRAllC_M, () => { setShowRAllC_M(false) }, onConfirmRemoveAll, 'Do you really want to remove all visibility data?')}
      <CustomCamera cameraType={'back'} 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={'Save'} onPress={() => { onSubmitData() }} />
          </View>
        </View>

      </LinearGradient>

    </Container>
  );
}



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