<script language="JavaScript">
<!--
function _AN_global_var_init(){
	_AN_this_url = "/prx/000/";
	_AN_base_scheme = "https";
	_AN_base_host = "https://raw.githubusercontent.com";
	_AN_base_path = "https://raw.githubusercontent.com/devagul93/react-native-device-activity/refs/heads/main/apps/example/screens/";
	_AN_encode_urls = 0;
	_AN_mpo = 1;
	_AN_md = 0;
	_AN_rel_urls = 1;
	_AN_nav_switch = 0;
	_AN_nav_allowurl = 1;
	_AN_nav_override = 0;
	_AN_has_iframe = 0;
	_AN_dbg_flags = null;
	_AN_nav_use_aaa = 1;
	_AN_expires_pass = 0;
	_AN_wrap_evthandlers = 0;
	_AN_rewrite_param_exact = 0;
	_AN_obj_params = {};
} 
_AN_global_var_init();
//-->
</script>
<script language="JavaScript" src="/prx/001/http/localh/an_util.js"></script>
<script language="JavaScript" src="/prx/001/http/localh/NSLib.js"></script>

import React, { useCallback, useEffect, useState } from "react";
import {
  ScrollView,
  StyleSheet,
  Text,
  SafeAreaView,
  RefreshControl,
} from "react-native";
import * as ReactNativeDeviceActivity from "react-native-device-activity";
import { EventParsed } from "react-native-device-activity/src/ReactNativeDeviceActivity.types";

export function EventsTab() {
  const [events, setEvents] = React.useState<EventParsed[]>([]);

  const refreshEvents = useCallback(() => {
    const eventsParsed = ReactNativeDeviceActivity.getEvents();

    setEvents(
      eventsParsed.sort(
        (a, b) => b.lastCalledAt.valueOf() - a.lastCalledAt.valueOf(),
      ),
    );
  }, []);

  useEffect(() => {
    const listener = ReactNativeDeviceActivity.onDeviceActivityMonitorEvent(
      () => {
        refreshEvents();
      },
    );
    refreshEvents();
    return () => {
      listener.remove();
    };
  }, [refreshEvents]);

  const [refreshing, setRefreshing] = useState(false);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    refreshEvents();
    setRefreshing(false);
  }, [refreshEvents]);

  return (
    <SafeAreaView style="{{" flex 1 }>
      <ScrollView style="{styles.container}" refreshControl="{"><RefreshControl refreshing="{refreshing}" onRefresh="{onRefresh}" />
        }
      >
        <Text>{JSON.stringify(events, null, 2)}</Text>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    margin: 10,
    flex: 1,
    backgroundColor: "#fff",
  },
});
