// import { useState, useRef, useCallback } from "react";
// import Container from "../../components/container";
// import { useFocusEffect, useRoute } from "@react-navigation/native";
// import { customStyles, GetPageTheme } from "../../styles/Global";
// import {
//   Image,
//   View,
//   Text,
//   ScrollView,
//   TouchableOpacity,
//   Platform,
//   FlatList,
// } from "react-native";
// import {
//   connect
// } from "react-redux";
// import {
//   mapStateToProps,
//   mapDispatchToProps,
// } from "../../reducers/contextProvider";
// import moment from "moment";
// import CustomHeader from "../../components/customHeader";
// import {
//   Ionicons,
// } from "../../components/icons";
// import LinearGradient from "react-native-linear-gradient";
// import { _checkLocationPermission } from "../../components/geolocation";

// import { db } from "../../constants/constants";
// import VideoIcon from "../../assets/image/VideoIcon.svg"
// import AudioIcon from "../../assets/image/Aud_Icon.svg"


// const GyancastCard = ({ icon, title, duration, description, props, item }) => {
//   const date1 = moment();
//   const date2 = moment(item?.ExpiryDate, "DD/MM/YYYY");

//   const daysDifference = date2.diff(date1, 'days');

//   let expiredCon = ((item?.Status == "Pending") || (item?.Status == "Progress")) && (daysDifference < 0)
//   let expiredConCur = ((item?.Status == "Pending") || (item?.Status == "Progress")) && (daysDifference == 0)

//   return (
//     <TouchableOpacity
//       onPress={() => {
//         props.navigation.navigate("PodcastDetails", { item: item });
//       }}
//       style={{
//         flexDirection: "row",
//         alignItems: "flex-start",
//         backgroundColor: expiredCon ? "#ffe6e6" : "#eff9fdff",
//         borderRadius: 12,
//         padding: 12,
//         marginVertical: 8,
//         marginHorizontal: 8,
//         shadowColor: "#000",
//         shadowOpacity: 0.05,
//         shadowRadius: 4,
//         shadowOffset: { width: 0, height: 2 },
//         elevation: 2,
//       }}
//     >
//       <View
//         style={{
//           width: 56,
//           height: 56,
//           borderRadius: 16,
//           backgroundColor: "#e6f0fa",
//           alignItems: "center",
//           justifyContent: "center",
//           marginRight: 12,
//         }}
//       >
//         <Image
//           source={{ uri: item?.Thumnail }}
//           style={{ width: 50, height: 50, borderRadius: 16 }}
//           resizeMode="contain"
//         />
//         <TouchableOpacity style={{ position: "absolute", padding: "15%", borderRadius: 16, backgroundColor: "rgba(128, 128, 128, 0.4)" }} onPress={() => { }}>

//           {item?.MediaType === 'Audio' ? (<AudioIcon width={32} height={32} />) : (<VideoIcon width={32} height={32} />)}

//         </TouchableOpacity>
//       </View>


//       <View style={{ flex: 1 }}>
//         <Text
//           style={{
//             fontWeight: "bold",
//             fontSize: 16,
//             color: "#222",
//             marginBottom: 2,
//           }}
//         >
//           {title}
//         </Text>
//         {item?.Status == "Complete" &&
//           <View style={{ position: "absolute", top: 0, right: -5 }}>
//             <Ionicons name='checkmark-done-sharp' color='green' size={20} />
//           </View>
//         }
//         <Text style={{ color: "#555", fontSize: 12, marginBottom: 6, fontWeight: "bold" }}>
//           Publish-{item?.PublishDate} <Text style={{ color: expiredCon ? "#ff6666" : expiredConCur ? "#ff9933" : "#555" }}> {expiredCon ? "Expired" : "Expiry"} -{item?.ExpiryDate}</Text>
//         </Text>
//         <Text style={{ color: "#888", fontSize: 15 }} numberOfLines={2}>
//           {description}
//         </Text>
//       </View>
//     </TouchableOpacity>
//   )
// };

// function Gyancasts(props) {
//   const route = useRoute();

//   const ST = props.StaticText || {};

//   const PageTheme = GetPageTheme(props.DarkMode, route.name);
//   const customStyle = customStyles(props.DarkMode, route.name);
//   const [Index, setIndex] = useState(0);

//   const [TrainingOrg, setTrainingOrg] = useState([]);
//   const [FilterDT, setFilterDT] = useState([]);

//   const IndexRef = useRef(0);

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

//   async function getData() {
//     try {
//       let List = [];
//       await db.transaction(async function (txn) {
//         let q = `Select TrainingId,Topic,Description,MediaType,TrainingContentId,Thumnail,TrainingUrl,Status,StartTime,PublishDate,ExpiryDate,DefaultLang,TrainingNo from Gyancast_TrainingContent where (DefaultLang="true" or DefaultLang =1 or DefaultLang = true or DefaultLang ='1') order by ExpiryDate`;

//         console.log("query---", q)
//         await txn.executeSql(
//           q,
//           [],
//           async function (txn2, txnres2) {
//             console.log("txnres2.rows.length:", txnres2.rows.length);
//             if (txnres2.rows.length > 0) {
//               for (let i = 0; i < txnres2.rows.length; i++) {
//                 let data = txnres2.rows.item(i);
//                 List.push(data);
//               }
//               setTrainingOrg(List);
//               setFilterDT(List);
//               filterListData(IndexRef.current, List);

//             }
//           },
//           function (txnE, txnerr) {
//             console.log(txnerr);
//           }
//         );
//       });
//     } catch (err) {
//       console.log(err);
//     }
//   }


//   function filterListData(val, List = []) {
//     let TrainingOrgVal = List.length > 0 ? List : TrainingOrg
//     console.log("TrainingOrgVal------", JSON.stringify(TrainingOrgVal))
//     if (val == 1) {
//       setFilterDT(TrainingOrgVal.filter((itm) => (itm.Status == "Pending") || (itm?.Status == "Progress")));
//     } else if (val == 2) {
//       setFilterDT(TrainingOrgVal.filter((itm) => itm.Status == "Complete"));
//     } else {
//       setFilterDT(
//         TrainingOrgVal.filter(
//           (item) =>
//             item?.Status === "Pending" &&
//             moment(item?.ExpiryDate, "DD/MM/YYYY").diff(moment(), "days") > 0 &&
//             (item?.StartTime === "00:00:00" ||
//               item?.StartTime === "00:00" ||
//               item?.StartTime === "0")
//         )
//       );
//     }
//     setIndex(val);
//     IndexRef.current = val
//   }

//   const HeaderTabs = () => {
//     return (
//       <View style={customStyle.storeTab_Con}>
//         <ScrollView
//           style={customStyle.storeTab_MenuCon2}
//           contentContainerStyle={customStyle.storeTab_Menu}
//           horizontal={true}
//         >
//           <TouchableOpacity
//             style={[
//               customStyle.storeTab_pill,
//               Index == 0 ? customStyle.storeTab_pillActive2 : {},
//             ]}
//             onPress={() => {
//               filterListData(0);
//             }}
//           >
//             <Text
//               style={[
//                 customStyle.storeTab_pillText,
//                 Index == 0
//                   ? customStyle.storeTab_pillActiveText
//                   : { color: PageTheme.$text_color },
//               ]}
//             >
//               {"New"}
//             </Text>
//           </TouchableOpacity>
//           <TouchableOpacity
//             style={[
//               customStyle.storeTab_pill,
//               Index == 1 ? customStyle.storeTab_pillActive2 : {},
//             ]}
//             onPress={() => {
//               filterListData(1);
//             }}
//           >
//             <Text
//               style={[
//                 customStyle.storeTab_pillText,
//                 Index == 1
//                   ? customStyle.storeTab_pillActiveText
//                   : { color: PageTheme.$text_color },
//               ]}
//             >
//               {"Pending"}
//             </Text>
//           </TouchableOpacity>

//           <TouchableOpacity
//             style={[
//               customStyle.storeTab_pill,
//               Index == 2 ? customStyle.storeTab_pillActive2 : {},
//               // { marginRight: "8%" },
//             ]}
//             onPress={() => {
//               filterListData(2);
//             }}
//           >
//             <Text
//               style={[
//                 customStyle.storeTab_pillText,
//                 Index == 2
//                   ? customStyle.storeTab_pillActiveText
//                   : { color: PageTheme.$text_color },
//               ]}
//             >
//               {"Completed"}
//             </Text>
//           </TouchableOpacity>

//           {/* <TouchableOpacity
//             style={customStyle.storel_searchBtn2}
//             onPress={() => {
//               FilterStores(searchedItem);
//             }}
//           >
//             <AntDesign
//               style={customStyle.storel_searchBtnIcon}
//               name="search1"
//               size={18}
//               color={"#0077C7"}
//             />
//           </TouchableOpacity> */}
//         </ScrollView>
//       </View>
//     );
//   };


//   const hour = moment().hour();

//   return (
//     <Container
//       {...props}
//       pt={0}
//       avoidSafeArea={Platform.OS == "ios" ? true : false}
//     >
//       <View style={{ zIndex: 10 }}>
//         <CustomHeader {...props} showaddstore={true} title={"GyanCast"} />
//       </View>

//       <LinearGradient
//         colors={[PageTheme.$gradient1, PageTheme.$primary_color]}
//         start={{ x: 0, y: 0 }}
//         end={{ x: 1, y: 0 }}
//         style={customStyle.roundScrollWrapper}
//       >
//         <View style={customStyle.pageContentWrapper}>
//           <View style={[customStyle.storelist_parentwrap]}>
//             <HeaderTabs />
//             <Text style={customStyle.GyanTitle}>
//               {hour < 12 ? 'Good Morning' : hour < 17 ? 'Good Afternoon' : 'Good Evening'}, {props?.UserId}
//             </Text>

//             {FilterDT.length <= 0 ? (
//               <View style={customStyle.noDataCon}>
//                 <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
//               </View>
//             ) : (
//               <View style={customStyle.storel_Con}>
//                 <FlatList
//                   data={FilterDT}
//                   style={customStyle.listcon}
//                   initialNumToRender={4}
//                   contentContainerStyle={customStyle.iteml_con}
//                   renderItem={({ item }) => (
//                     <GyancastCard
//                       icon={item.icon}
//                       title={item.Topic}
//                       duration={item.StartTime}
//                       description={item.Description}
//                       item={item}
//                       props={props}
//                     />
//                   )}
//                 />
//               </View>
//             )}
//           </View>
//         </View>
//       </LinearGradient>
//     </Container>
//   );
// }

// export default connect(mapStateToProps, mapDispatchToProps)(Gyancasts);

import { useState, useRef, useCallback, useEffect } from "react";
import Container from "../../components/container";
import { useFocusEffect, useRoute } from "@react-navigation/native";
import { customStyles, GetPageTheme } from "../../styles/Global";
import {
  Image,
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  Platform,
  FlatList,
  BackHandler,
} from "react-native";
import {
  connect
} from "react-redux";
import {
  mapStateToProps,
  mapDispatchToProps,
} from "../../reducers/contextProvider";
import moment from "moment";
import CustomHeader from "../../components/customHeader";
import {
  Ionicons,
} from "../../components/icons";
import LinearGradient from "react-native-linear-gradient";
import { _checkLocationPermission } from "../../components/geolocation";
import { db } from "../../constants/constants";
import VideoIcon from "../../assets/image/VideoIcon.svg"
import AudioIcon from "../../assets/image/Aud_Icon.svg"


const GyancastCard = ({ icon, title, duration, description, props, item }) => {
  const date1 = moment();
  const date2 = moment(item?.ExpiryDate, "DD/MM/YYYY");

  const daysDifference = date2.diff(date1, 'days');

  let expiredCon = ((item?.Status == "Pending") || (item?.Status == "Progress")) && (daysDifference < 0)
  let expiredConCur = ((item?.Status == "Pending") || (item?.Status == "Progress")) && (daysDifference == 0)

  return (
    <TouchableOpacity
      onPress={() => {
        props.navigation.navigate("PodcastDetails", { item: item });
      }}
      style={{
        flexDirection: "row",
        alignItems: "flex-start",
        backgroundColor: expiredCon ? "#ffe6e6" : "#eff9fdff",
        borderRadius: 12,
        padding: 12,
        marginVertical: 8,
        marginHorizontal: 8,
        shadowColor: "#000",
        shadowOpacity: 0.05,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 2,
      }}
    >
      <View
        style={{
          width: 56,
          height: 56,
          borderRadius: 16,
          backgroundColor: "#e6f0fa",
          alignItems: "center",
          justifyContent: "center",
          marginRight: 12,
        }}
      >
        <Image
          source={{ uri: item?.Thumnail }}
          style={{ width: 50, height: 50, borderRadius: 16 }}
          resizeMode="contain"
        />
        <TouchableOpacity style={{ position: "absolute", padding: "15%", borderRadius: 16, backgroundColor: "rgba(128, 128, 128, 0.4)" }} onPress={() => { }}>
          {item?.MediaType === 'Audio' ? (<AudioIcon width={32} height={32} />) : (<VideoIcon width={32} height={32} />)}
        </TouchableOpacity>
      </View>


      <View style={{ flex: 1 }}>
        <Text
          style={{
            fontWeight: "bold",
            fontSize: 16,
            color: "#222",
            marginBottom: 2,
          }}
        >
          {title}
        </Text>
        {item?.Status == "Complete" &&
          <View style={{ position: "absolute", top: 0, right: -5 }}>
            <Ionicons name='checkmark-done-sharp' color='green' size={20} />
          </View>
        }
        <Text style={{ color: "#555", fontSize: 12, marginBottom: 6, fontWeight: "bold" }}>
          Publish-{item?.PublishDate} <Text style={{ color: expiredCon ? "#ff6666" : expiredConCur ? "#ff9933" : "#555" }}> {expiredCon ? "Expired" : "Expiry"} -{item?.ExpiryDate}</Text>
        </Text>
        <Text style={{ color: "#888", fontSize: 15 }} numberOfLines={2}>
          {description}
        </Text>
      </View>
    </TouchableOpacity>
  )
};

function Gyancasts(props) {
  const route = useRoute();
  const ST = props.StaticText || {};
  const route_params = route?.params || {}
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const [Index, setIndex] = useState(0);
  const [TrainingOrg, setTrainingOrg] = useState([]);
  const [FilterDT, setFilterDT] = useState([]);
  const [backPressStatus, setBackPressStatus] = useState(true);
  const backPressStatusRef = useRef(true);
  const IndexRef = useRef(0);

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

  useFocusEffect(
    useCallback(() => {
      const onBackPress = () => {
        if (!backPressStatusRef.current) {
          // ❌ block hardware back
          return true;
        }

        // ✅ allow back
        props.navigation.goBack();
        return true;
      };

      const backHandler = BackHandler.addEventListener(
        'hardwareBackPress',
        onBackPress
      );

      return () => {
        backHandler.remove(); // ✅ RN 0.81 way
      };
    }, [])
  );




  async function getData() {
    try {
      let List = [];
      db.transaction(function (txn) {
        let q = `Select TrainingId,Topic,Description,MediaType,TrainingContentId,Thumnail,TrainingUrl,Status,StartTime,PublishDate,ExpiryDate,DefaultLang,TrainingNo from Gyancast_TrainingContent where (DefaultLang="true" or DefaultLang =1 or DefaultLang = true or DefaultLang ='1') order by ExpiryDate`;
        console.log("query---", q)
        txn.executeSql(
          q,
          [],
          function (txn2, txnres2) {
            console.log("txnres2.rows.length:", txnres2.rows.length);
            if (txnres2.rows.length > 0) {
              for (let i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);
                List.push(data);
              }
              console.log("list_ddddd", List)
              let d2 = moment().format('DD/MM/YYYY');
              const todayItems = List.filter(item => item?.ExpiryDate === d2);
              console.log(todayItems.length, d2);

              if (todayItems !== undefined && todayItems.length > 0 && route_params !== undefined && route_params?.PopupId == 1) {
                const allCompletedToday = todayItems.every(item => item?.Status === 'Complete');
                console.log("allCompletedToday", allCompletedToday);
                if (allCompletedToday) {
                  setBackPressStatus(true)
                  backPressStatusRef.current = true
                  db.transaction(function (txn) {
                    // delete all today data
                    txn.executeSql(`delete from Gyancast_PopupMessage where 1=1`, [], function (txn1, txnres) {
                      console.log('deleted all data for Gyancast_PopupMessage');
                    }, function (Etxn, err) {
                      console.log('err:', err);
                    });
                  });
                } else {
                  setBackPressStatus(false)
                  backPressStatusRef.current = false
                }
              }

              setTrainingOrg(List);
              setFilterDT(List);
              filterListData((route_params !== undefined && route_params?.PopupId == 1) ? 1 : IndexRef.current, List);
            }
          },
          function (txnE, txnerr) {
            console.log(txnerr);
          }
        );
      });
    } catch (err) {
      console.log(err);
    }
  }

  function filterListData(val, List = []) {
    let TrainingOrgVal = List.length > 0 ? List : TrainingOrg
    console.log("TrainingOrgVal------", typeof (val), val, JSON.stringify(TrainingOrgVal))
    if (val == 1) {
      setFilterDT(TrainingOrgVal.filter((itm) => (itm.Status == "Pending") || (itm?.Status == "Progress")));
    } else if (val == 2) {
      setFilterDT(TrainingOrgVal.filter((itm) => itm.Status == "Complete"));
    } else {
      setFilterDT(
        TrainingOrgVal.filter(
          (item) =>
            item?.Status === "Pending" &&
            moment(item?.ExpiryDate, "DD/MM/YYYY").diff(moment(), "days") > 0 &&
            (item?.StartTime === "00:00:00" ||
              item?.StartTime === "00:00" ||
              item?.StartTime === "0")
        )
      );
    }
    setIndex(val);
    IndexRef.current = val
  }

  const HeaderTabs = () => {
    return (
      <View style={customStyle.storeTab_Con}>
        <ScrollView
          style={customStyle.storeTab_MenuCon2}
          contentContainerStyle={customStyle.storeTab_Menu}
          horizontal={true}
        >
          <TouchableOpacity
            style={[
              customStyle.storeTab_pill,
              Index == 0 ? customStyle.storeTab_pillActive2 : {},
            ]}
            onPress={() => {
              filterListData(0);
            }}
          >
            <Text
              style={[
                customStyle.storeTab_pillText,
                Index == 0
                  ? customStyle.storeTab_pillActiveText
                  : { color: PageTheme.$text_color },
              ]}
            >
              {"New"}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[
              customStyle.storeTab_pill,
              Index == 1 ? customStyle.storeTab_pillActive2 : {},
            ]}
            onPress={() => {
              filterListData(1);
            }}
          >
            <Text
              style={[
                customStyle.storeTab_pillText,
                Index == 1
                  ? customStyle.storeTab_pillActiveText
                  : { color: PageTheme.$text_color },
              ]}
            >
              {"Pending"}
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[
              customStyle.storeTab_pill,
              Index == 2 ? customStyle.storeTab_pillActive2 : {},
              // { marginRight: "8%" },
            ]}
            onPress={() => {
              filterListData(2);
            }}
          >
            <Text
              style={[
                customStyle.storeTab_pillText,
                Index == 2
                  ? customStyle.storeTab_pillActiveText
                  : { color: PageTheme.$text_color },
              ]}
            >
              {"Completed"}
            </Text>
          </TouchableOpacity>
        </ScrollView>
      </View>
    );
  };


  const hour = moment().hour();

  return (
    <Container
      {...props}
      pt={0}
      avoidSafeArea={Platform.OS == "ios" ? true : false}
    >
      <View style={{ zIndex: 10 }}>
        <CustomHeader {...props} showaddstore={true} title={"GyanCast"} onPress={() => {
          if (backPressStatus) {
            props.navigation.goBack();
          }
        }} />
      </View>

      <LinearGradient
        colors={[PageTheme.$gradient1, PageTheme.$primary_color]}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 0 }}
        style={customStyle.roundScrollWrapper}
      >
        <View style={customStyle.pageContentWrapper}>
          <View style={[customStyle.storelist_parentwrap]}>
            <HeaderTabs />
            <Text style={customStyle.GyanTitle}>
              {hour < 12 ? 'Good Morning' : hour < 17 ? 'Good Afternoon' : 'Good Evening'}, {props?.UserId}
            </Text>

            {FilterDT.length <= 0 ? (
              <View style={customStyle.noDataCon}>
                <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
              </View>
            ) : (
              <View style={customStyle.storel_Con}>
                <FlatList
                  data={FilterDT}
                  style={customStyle.listcon}
                  initialNumToRender={4}
                  keyExtractor={(item, index) => item.TrainingContentId?.toString() || index.toString()}
                  contentContainerStyle={customStyle.iteml_con}
                  renderItem={({ item }) => (
                    <GyancastCard
                      icon={item?.icon}
                      title={item?.Topic}
                      duration={item?.StartTime}
                      description={item?.Description}
                      item={item}
                      props={props}
                    />
                  )}
                />
              </View>
            )}
          </View>
        </View>
      </LinearGradient>
    </Container>
  );
}

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

