import React, { useState, useCallback } from 'react';
import Container from '../components/container';
import { useRoute, useFocusEffect } from '@react-navigation/native';
import { customStyles, GetPageTheme } from '../styles/Global';
import { View, Text, TouchableOpacity, Platform, FlatList, Linking } from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import moment from 'moment';
import { db } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { useNavigation } from '@react-navigation/native';
import { getKPIFields } from '../controller/functions';

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 [processing, setProcessing] = useState(true);
  const [isDataFound, setisDataFound] = useState(false);
  const [miscMenuList, setMiscMenuData] = useState('');
  const [uploadedStoreText, setUploadedStoreText] = useState('');
  const navigation = useNavigation();
  const d1 = new Date();
  const d2 = moment(d1).format('MM/DD/YYYY');

  useFocusEffect(useCallback(
    () => {
      getData();
    }, []));


  async function getData() {
    try {
      setProcessing(true);
      db.transaction((txn) => {
        const menuQuery = `SELECT DISTINCT MenuId, MenuName, ScreenName FROM Mapping_SideMenuMiscellaneous ORDER BY DisplayOrder`;
        const storeIdQuery = `SELECT DISTINCT STORE_ID FROM OFFLINE_ORDER ORDER BY STORE_ID`;
        // First: Fetch Menu
        txn.executeSql(menuQuery, [], (txn2, txnres) => {
          const len = txnres.rows.length;
          const menuArr = [];
          for (let i = 0; i < len; i++) {
            menuArr.push(txnres.rows.item(i));
          }
          setMiscMenuData(menuArr); // show menus

          // Second: Fetch uploaded StoreIds
          txn.executeSql(storeIdQuery, [], (txn3, storeRes) => {
            const slen = storeRes.rows.length;
            const storeIdArr = [];
            for (let i = 0; i < slen; i++) {
              storeIdArr.push(storeRes.rows.item(i).STORE_ID);
            }

            console.log("storeIdArr.length", storeIdArr.length)
            const uploadedText = storeIdArr.length > 0
              ? `Uploaded data of StoreId(s): ${storeIdArr.join(', ')}`
              : '';

            console.log("uploaded text:", uploadedText)
            setUploadedStoreText(uploadedText); // <-- use this in your UI
            setProcessing(false);
          }, (txn3, err3) => {
            console.error("Store ID query error:", err3);
            setUploadedStoreText('');
            setProcessing(false);
          });

        }, (txn2, err2) => {
          console.error("Menu fetch error:", err2);
          setMiscMenuData([]);
          setProcessing(false);
        });
      });

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


  const openWebLink = async (item) => {
    // Check if the device can open the URL
    //console.log("items", item)
    let AllKPIFields = await getKPIFields(item);
    // console.log("items", AllKPIFields)
    let isColor_MSLIndex = AllKPIFields.findIndex(i => i.KPIFieldName == 'Ppay_ExternalLink')
    let isColor_MSLObj = isColor_MSLIndex >= 0 ? AllKPIFields[isColor_MSLIndex] : {};
    let isColor_MSLEnable = isColor_MSLIndex >= 0 ? isColor_MSLObj['KPIFieldEnable'] : false;
    let Ppay_ExternalLink = isColor_MSLEnable && isColor_MSLIndex >= 0 ? isColor_MSLObj['KPIFieldDisplayName'] : ""
    if (Ppay_ExternalLink !== "") {
      let modifyPpay_link = Ppay_ExternalLink + "?ProjectCode=" + props.projectCode + "&UserId=" + props.UserId
      console.log("ppay_link", modifyPpay_link)
      const supported = await Linking.canOpenURL(modifyPpay_link);
      if (supported) {
        await Linking.openURL(modifyPpay_link);
      } else {
        console.log("Don't know how to open URI: " + modifyPpay_link);
      }
    }
  };
  const handlePress = (item) => {
    console.log("Pressed item:", item);
    if (item.ScreenName === "ORDER") {
      navigation.navigate("OfflineOrder", { item });
    } else if (item.ScreenName === "TRAINHOLIDAYONEAPP") {
      navigation.navigate('TrainingMenu', { 'Contentid': 1, item })
    } else if (item.ScreenName === "GROOMINGIMG") {
      navigation.navigate('GroomingPictures', { 'storeData': {} })
    } else if (item?.ScreenName === "PPAY") {
      openWebLink(item)
    }

    
    else {
      console.log("Unknown ScreenName:", item.ScreenName);
    }
  };


  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS == 'ios' ? true : false}>
      {processing && <CustomLoader title={ST.Loading + '...'} />}
      <CustomHeader {...props} showaddstore={true} title={'Miscellaneous'} />
      <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={{ padding: 16 }}>
            <FlatList
              data={miscMenuList}
              keyExtractor={(item) => item.MenuId.toString()}
              renderItem={({ item }) => (
                <TouchableOpacity
                  onPress={() => handlePress(item)}
                  style={{
                    backgroundColor: PageTheme.$primary_color,
                    padding: 16,
                    marginBottom: 10,
                    borderRadius: 8
                  }}
                >
                  <Text style={{ color: '#fff', fontSize: 16 }}>
                    {item.MenuName}
                  </Text>
                </TouchableOpacity>
              )}
              ListEmptyComponent={() =>
              (<Text style={{ textAlign: 'center', color: '#999' }}>
                No menu items found.
              </Text>
              )

              }
            />

          </View>

        </View>
      </LinearGradient>
    </Container>
  );
}

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