import React, { useState, useEffect } from 'react';
import { StyleSheet } from 'react-native';
import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { LinearGradient } from 'expo-linear-gradient';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';

const API_KEY = process.env.EXPO_PUBLIC_API_KEY;
const BASE_URL = process.env.EXPO_PUBLIC_BASE_URL;

export default function HomeScreen() {
  const [message, setMessage] = useState('Loading message...');

  useEffect(() => {
    fetchMessage();
    const intervalId = setInterval(fetchMessage, 10000); // Every 10 seconds
    return () => clearInterval(intervalId);
  }, []);

  const fetchMessage = async () => {
    try {
      const storedUser = await AsyncStorage.getItem('@user');
      if (!storedUser) {
        setMessage('User not found. Please select a user.');
        return;
      }

      const user = JSON.parse(storedUser);
      //const otherUserId = user.id === 1 ? 2 : 1;

      const response = await axios.get(`${BASE_URL}/getMessage`, {
        params: { apiKey: API_KEY, userId: user.id }
      });

      if (response.data && response.data[0] && response.data[0].receivedMessage) {
        setMessage(response.data[0].receivedMessage);
      } else {
        setMessage('No message found.');
      }
    } catch (error) {
      console.error('API call error:', error);
      setMessage('Failed to fetch message. Please try again.');
    }
  };

  return (
    <LinearGradient
      colors={['#F67C0A', '#F60AD3']}
      style={styles.container}
      start={{ x: 0, y: 0 }}
      end={{ x: 1, y: 1 }}
    >
      <ThemedView style={styles.container}>
        <ThemedText style={styles.title}>{message}</ThemedText>
      </ThemedView>
    </LinearGradient>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
  title: {
    fontSize: 56,
    lineHeight: 72,
    fontWeight: 'bold',
    marginBottom: 20,
    textAlign: 'center',
    paddingHorizontal: 20,
  },
});
