import React, { useEffect, useState } from "react";
import { StyleSheet, Alert } from "react-native";
import { ThemedText } from "@/components/ThemedText";
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 TestPush = () => {
  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 (
    <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>
  );

};
export default TestPush;

const styles = StyleSheet.create({
  buttonLabel: {
    fontSize: 16,
  },
  buttonIcon: {
    paddingRight: 8,
  },
});
