import React, { useState, useEffect } from 'react';
import { 
  StyleSheet, 
  TextInput, 
  TouchableOpacity, 
  Alert, 
  Keyboard, 
  TouchableWithoutFeedback,
  KeyboardAvoidingView,
  Platform, 
  SafeAreaView,  // SafeAreaView import for handling safe areas
  View 
} from 'react-native';
import { ThemedText } from '@/components/ThemedText';
import { LinearGradient } from 'expo-linear-gradient';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';

// Environment variables
const API_KEY = process.env.EXPO_PUBLIC_API_KEY;
const BASE_URL = process.env.EXPO_PUBLIC_BASE_URL;

export default function SendMessageScreen() {
  const [message, setMessage] = useState('');
  const [userId, setUserId] = useState<number | null>(null); // Use number type for userId
  const [inputHeight, setInputHeight] = useState(120); // Set initial height for TextInput

  // Update TextInput height dynamically
  const updateInputHeight = (height: number) => {
    setInputHeight(Math.max(120, height)); // Ensure it doesn't shrink below 120px
  };

  // On component mount, get the user ID from AsyncStorage
  useEffect(() => {
    const getUserId = async () => {
      try {
        const storedUser = await AsyncStorage.getItem('@user');
        if (storedUser) {
          const user = JSON.parse(storedUser);
          setUserId(user.id);
        }
      } catch (error) {
        console.error('Failed to get user ID:', error);
      }
    };

    getUserId();
  }, []);

  // Function to send a message
  const sendMessage = async () => {
    // Input validation
    if (!message.trim()) {
      Alert.alert('Error', 'Please enter a message');
      return;
    }

    if (!userId) {
      Alert.alert('Error', 'User not found. Please select a user first.');
      return;
    }

    try {
      await axios.post(`${BASE_URL}/setMessage`, null, {
        params: { apiKey: API_KEY, userId, message }
      });
      Alert.alert('Success', 'Message sent successfully');
      setMessage(''); // Clear the message input on success
      Keyboard.dismiss(); // Dismiss the keyboard
    } catch (error) {
      console.error('Failed to send message:', error);
      Alert.alert('Error', 'Failed to send message. Please try again.');
    }
  };

  return (
    // Ensure keyboard behaves correctly on both iOS and Android
    <KeyboardAvoidingView 
      behavior={Platform.OS === "ios" ? "padding" : "height"} 
      style={{ flex: 1 }}
    >
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        {/* SafeAreaView for notch and layout safety */}
        <SafeAreaView style={styles.safeContainer}>
          <LinearGradient
            colors={['#F67C0A', '#F60AD3']}
            style={styles.container}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
          >
            <View style={styles.chatContainer}>
              <TextInput
                style={[styles.input, { height: inputHeight }]} // Dynamic height
                value={message}
                onChangeText={setMessage}
                placeholder="Write a message"
                placeholderTextColor="#FFFFFF"
                multiline // Allows multiple lines
                numberOfLines={4}
                textAlignVertical="top" // Align text at the top
                onContentSizeChange={(event) => 
                  updateInputHeight(event.nativeEvent.contentSize.height)
                }
              />

              {/* Send Message Button */}
              <TouchableOpacity style={styles.button} onPress={sendMessage}>
                <ThemedText style={styles.buttonText}>Send Message</ThemedText>
              </TouchableOpacity>
            </View>
          </LinearGradient>
        </SafeAreaView>
      </TouchableWithoutFeedback>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  safeContainer: {
    flex: 1,  
    backgroundColor: 'transparent', // Ensure full-screen safe area
  },
  container: {
    flex: 1,
    backgroundColor: 'transparent',
  },
  chatContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 20, // Ensures padding around the input and button
  },
  input: {
    width: '100%',
    minHeight: 150,  // Minimum height for the TextInput
    borderColor: 'transparent',
    borderWidth: 1,
    borderRadius: 10,
    padding: 10,
    marginBottom: 10,
    fontSize: 32, // Adjust font size to shrink for smaller devices
    lineHeight: 40, // Adjust line height for better readability
    textAlign: 'center',
    color: '#FFFFFF',
    fontWeight: 'bold',
    //backgroundColor: 'rgba(0, 0, 0, 0.1)', // Subtle background for text input
    backgroundColor: 'transparent', // Transparent background
  },
  button: {
    backgroundColor: '#730FF8',
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 10,
  },
  buttonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
});