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 styles from '../styles/TrainingMenu.style';
import {Image, View, Text, ScrollView, TouchableOpacity, Platform, Dimensions} from 'react-native';
import {connect} from 'react-redux';
import {mapStateToProps, mapDispatchToProps} from '../reducers/contextProvider';
import moment from 'moment';
import {get_item} from '../components/localStorage';
import {db, colors_Arr} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {AntDesign} from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import NoDataComponent from '../components/NoDataComponent';
import LinearGradient from 'react-native-linear-gradient';
import grey_bg_image from '../assets/performics/circle_grey.svg';

function TrainingMenu(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 [webviewurl, setWebviewurl] = useState(false);
  const [processing, setProcessing] = useState(true);
  const [isDataFound, setisDataFound] = useState(false);
  const [reportData, setReportData] = useState([]);
  const [designation, setDesignation] = useState('');
  const [CardViewEnable, setCardViewEnable] = useState(false);
  const [CardViewConfig, setCardViewConfig] = useState({});

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

  useEffect(() => {
    getData();
  }, []);

  const [activeTab, setActiveTab] = useState(0);

  const [userhomelocationdata , setUserHomeLocationData] = useState([]);

  const scrollViewRef = useRef(null);
  const tabWidth = Dimensions.get('window').width / 2; // Assuming 2 tabs, adjust this accordingly

  const tabs = [
    {title: 'Documents', content: _renderMenuList()},
    {title: 'Home', content: _renderMenuList('home')},
  ];

  const handleScroll = event => {
    const offsetX = event.nativeEvent.contentOffset.x;
    const index = Math.floor(offsetX / tabWidth);
    setActiveTab(index);
  };

  const scrollToTab = index => {
    scrollViewRef.current.scrollTo({x: index * tabWidth * 2, animated: true});
  };

  async function getData() {
    try {
      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      let desg = loginDetails.Designation || '';
      setDesignation(desg);
      await db.transaction(async function (txn) {
        let q = `Select distinct ContentTypeId, ContentType, IconPath, Icon, MediaType, DownloadKey, ReportView as ReportType, InnerScreenView from Master_DetailerContent group by ContentTypeId`;
        //   let q=`SELECT * from Master_MenuReports`;

        await txn.executeSql(
          q,
          [],
          async function (txn2, txnres) {
            console.log('txnres.rows.length:', txnres.rows.length);
            if (txnres.rows.length > 0) {
              let arr = [];
              let carView = true;
              for (var i = 0; i < txnres.rows.length; i++) {
                let data = txnres.rows.item(i);
                carView = data?.InnerScreenView == 'Tile';
                arr.push(data);
                if (i == txnres.rows.length - 1) {
                  setCardViewConfig(data);
                  setCardViewEnable(carView);
                  setReportData(arr);
                  setisDataFound(true);
                  setProcessing(false);
                }
              }
            } else {
              setProcessing(false);
            }
          },
          function (txn2, txnerr) {
            console.log(txnerr);
            setProcessing(false);
          },
        );
        
        let q1=`SELECT * from Master_UserHomeLocation`;
        await txn.executeSql(q1,[],async function (txn2, txnres) { 
            if(txnres.rows.length>0){
              let arr=[];
              for(var i=0;i<txnres.rows.length;i++){
                let data =txnres.rows.item(i);
                arr.push(data);
                if(i==txnres.rows.length-1){
                  console.log(arr, 'Arrrayyy')
                  setUserHomeLocationData(arr)
                  
                }
              }
            }
        },function (txnE,txnerr) { console.log(txnerr);},);
  
      });

     

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

  function gotoTraingPage(item) {
    if (item.MediaType == 'DB') {
      props.navigation.navigate('ReportDetail', {ReportData: item});
    } else if( item.ContentType === "Home Location"){
      props.navigation.navigate('HomeLocation')
    }else {
      props.navigation.navigate('Training', {
        Contentid: item.ContentTypeId,
        TrainingData: item,
      });
    }
  }

  function _renderLeftMenuItem(index, RowContent) {
    return (
      <View style={customStyle.dialyMenu_Rows} key={index}>
        {RowContent[0]}
      </View>
    );
  }

  function _renderMenuItem(item, index) {
    let newi;
    if (index == 1) {
      newi = '2';
    } else {
      newi = index > 2 ? index % 3 : index;
    }

    // let newi=index>2?((index%3)):index;
    let firstitem = index % 2 == 0 ? true : false;

    let arr = ['#bed3ea', '#bed3ea'];
    // let arr = ["#dcf2ee", "#30cfb0"];
    // let arr = colors_Arr[newi] ? colors_Arr[newi].bg : colors_Arr["0"].bg;
    let unavlbl_bg = ['#bfbfbf', '#bfbfbf'];
    let arr_new = item?.isAvlbl == false ? unavlbl_bg : arr;
    // let iconColor=colors_Arr[newi]?colors_Arr[newi].color:colors_Arr["0"].color;
    const imgPath = CardViewConfig?.IconPath + CardViewConfig?.Icon;

    let MbgImage = colors_Arr[newi]
      ? colors_Arr[newi]?.bgImage
      : colors_Arr['0']?.bgImage;
    MbgImage = item?.isAvlbl == false ? grey_bg_image : MbgImage;

    let hasSomeData = item?.hasSomeData;
    return (
      <TouchableOpacity activeOpacity={item.isAvlbl == false ? 1 : 0.7}
        style={[ customStyle.daily_menu_outer, firstitem ? customStyle.daily_menu_first : {},]}
        key={index}
        onPress={() => gotoTraingPage(item)}>
        <View style={customStyle.daily_menu_tilebgShadow}>
          <LinearGradient colors={arr_new} start={{x: 0, y: 0}} end={{x: 1, y: 1}} style={customStyle.daily_menu} />
          <View style={[customStyle.daily_menu_innerImgCon]}>
            <MbgImage width={90} height={90}
              style={customStyle.daily_menu_bgImg}
            />
          </View>
          <View style={[customStyle.daily_menu_inner2]}>
            {imgPath != null && imgPath != '' && (
              <Image
                source={{uri: imgPath}}
                style={customStyle.daily_menu_Icon}
              />
            )}
          </View>

          <Text style={customStyle.daily_menu_title}>{item.ContentType}</Text>
          {item.isDone == true && (
            <View style={customStyle.daily_menu_done}>
              <AntDesign color={'green'} size={30} name="checkcircle" />
            </View>
          )}
          {/* {item.hasSomeData==true && !item.isKPI_Done &&
              <View style={customStyle.daily_menu_hasData}><FontAwesome color={'green'} size={20} name='dot-circle-o'/></View>
            }
            {props.PartialSaveAllow==true && item.PSAllow!=null && item.PSAllow==true  &&
              <Text style={customStyle.daily_menu_Count}>{`(${item.DataDoneCount}/${item.DataRowAvlblCount})`}</Text>
            }   */}
        </View>
      </TouchableOpacity>
    );
  }

  function _renderRightMenuItem(item, index, RowContent) {
    return (
      <View style={customStyle.dialyMenu_Rows} key={index}>
        {RowContent[0]}
        {_renderMenuItem(item, index)}
      </View>
    );
  }

  function _renderMenuList(home) {
    var RowContent = [];
    let firstArr = [
      {
        ContentType: 'Home Location',
        ContentTypeId: 1,
        DownloadKey: '',
        Icon: 'Paid-Visibility.png',
        IconPath: 'https://di1.parinaam.in/Download/Icon/',
        InnerScreenView: 'Tile',
        MediaType: 'PDF',
        ReportType: '',
      },
    ];

    let isHome = userhomelocationdata[0]?.OptionShow == 1 && home === 'home' ? firstArr : reportData;
    return (
      isHome.length > 0 &&
      isHome.map((item, index) => {
        // let RowContent=[]
        if (CardViewEnable) {
          let firstitem = index % 2 == 0 ? true : false;

          if (firstitem) {
            var content = _renderMenuItem(item, index);
            RowContent = [content];
            if (index == isHome.length - 1) {
              return _renderLeftMenuItem(index, RowContent);
            }
          } else {
            return _renderRightMenuItem(item, index, RowContent);
          }
        } else {
          return (
            <TouchableOpacity
              style={[customStyle.reportMenuItem]}
              key={index}
              onPress={() => {
                gotoTraingPage(item);
              }}>
              <Text style={customStyle.reportMenuItemText}>
                {item.ContentType}
              </Text>
            </TouchableOpacity>
          );
        }
      })
    );
  }


  console.log(userhomelocationdata[0]?.OptionShow, 'user datta')

  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS == 'ios' ? true : false}>
      {processing && <CustomLoader title={ST.Loading + '...'} />}
      <CustomHeader {...props} showaddstore={true} title={'Misc. Documents'} />
      <LinearGradient
        colors={[PageTheme.$gradient1, PageTheme.$primary_color]}
        start={{x: 0, y: 0}}
        end={{x: 1, y: 0}}
        style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper]}>
          {!props.isDataDownloaded && <NoDataComponent {...props} />}
          {props.isDataDownloaded == true && (
            <View>
              {isDataFound == false && (
                <View style={customStyle.noDataCon}>
                  <Text style={customStyle.noDataText}>
                    {ST.NoDataAvailable}
                  </Text>
                </View>
              )}

              {isDataFound == true && (
                <ScrollView
                  contentContainerStyle={customStyle.rp_scrollViewInner}
                  style={customStyle.rp_scrollView}>
                  <View style={[customStyle.vlUinfo_Card]}>
                    <View
                      style={[
                        customStyle.vlUinfo_CardRow,
                        customStyle.vlUinfo_CardBorder,
                      ]}>
                      <Text style={customStyle.vlUinfo_lbl}>
                        {ST.Username + ' :'}
                      </Text>
                      <Text style={customStyle.vlUinfo_text}>
                        {props.UserId}
                      </Text>
                    </View>
                    <View style={customStyle.vlUinfo_CardRow}>
                      <Text style={customStyle.vlUinfo_lbl}>
                        {ST.Designation + ' :'}
                      </Text>
                      <Text style={customStyle.vlUinfo_text}>
                        {designation}
                      </Text>
                    </View>


                    {userhomelocationdata[0]?.OptionShow == 1 && 
                      <View style={styles.tabContainer}>
                        {tabs.map((tab, index) => (
                          <TouchableOpacity
                            key={index}
                            style={[
                              styles.tab,
                              activeTab === index && styles.activeTab,
                            ]}
                            onPress={() => scrollToTab(index)}>
                            <Text style={styles.tabText}>{tab.title}</Text>
                          </TouchableOpacity>
                        ))}
                      </View>
                     
                    }

                  </View>
                  <ScrollView
                    ref={scrollViewRef}
                    horizontal={userhomelocationdata[0]?.OptionShow == 1}
                    pagingEnabled
                    showsHorizontalScrollIndicator={false}
                    onScroll={handleScroll}
                    scrollEventThrottle={16}>
                    {tabs.map((tab, index) => {
                      let tabContent=null;
                      if(userhomelocationdata[0]?.OptionShow == 1 &&  tab.title=="Home"){
                        tabContent=tab.content
                      }else if(tab.title!="Home"){
                        tabContent=tab.content
                      }
                      return (
                        <View key={index} style={styles.contentContainer}>
                          {tabContent}
                        </View>
                    )})}
                  </ScrollView>
                </ScrollView>
              )}
            </View>
          )}
        </View>
      </LinearGradient>
    </Container>
  );
}

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