import React, { useEffect, useState } from "react";
import { StyleSheet, Alert } from "react-native";
import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import FontAwesome from "@expo/vector-icons/FontAwesome";
import Button from "@/components/buttons/Button";
import { getUserData } from "@/components/services/securestorage/UserData";

const Index = () => {
  const scheme = useColorScheme() ?? 'light';
  const [pushToken, setPushToken] = useState<string | null>(null);

  useEffect(() => {
    const fetchUserData = async () => {
      const userData = await getUserData();
      if (userData) {
        setPushToken(userData.pushToken);
      }
    };
    fetchUserData();
  }, []);

  const sendPushNotification = async () => {
    if (!pushToken) {
      Alert.alert('Error', 'Push token not available');
    return;
    }

    const message = {
      to: pushToken,
      sound: 'default',
      title: 'Hey Baby!',
      body: 'Are you ready for push notifications?!?',
      data: {
        someData: 'goes here'
      },
    };

    try {
      const response = await fetch(`https://exp.host/--/api/v2/push/send`, {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Accept-encoding': 'gzip, deflate',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(message),
      });

      const result = await response.json();
      console.log('Result:', result);
      Alert.alert('Success', 'Push notification sent successfully');

    } catch (error) {
      console.error('Error sending push notification:', error);
      Alert.alert('Error', 'Failed to send push notification');
    }
  };

  return (
    <ThemedView style={styles.container}>
      <ThemedText style={styles.text}>
        Home Screen
      </ThemedText>
      <ThemedView style={styles.footerContainer}>
        <Button width={220} height={60}
          onPress={sendPushNotification}
        >
        <FontAwesome name="bell" size={18}
          color={Colors[scheme].background} style={styles.buttonIcon}
        />
        <ThemedText
          style={[
            styles.buttonLabel,
            {color: Colors[scheme].background}
          ]}
        >
          Send Push Notification
        </ThemedText>
        </Button>
      </ThemedView>
    </ThemedView>
  );
}
export default Index;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 24,
  },
  footerContainer: {
    flex: 1 / 3, 
    alignItems: 'center',
  },
  buttonLabel: {
    fontSize: 16,
  },
  buttonIcon: {
    paddingRight: 8,
  },
});
