import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useTailwind } from 'tailwind-rn';
import socket from './services/socket';

function LoginScreen({ navigation, setUserToken }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [errorMessage, setErrorMessage] = useState('');


  const tailwind = useTailwind();

  async function loginUser() {
    try {
      setErrorMessage('');
      const apiUrl = await AsyncStorage.getItem('apiEndpoint')
      const response = await fetch(`${apiUrl}/api/v1/app/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error('Failed to login:', response.status, errorText);
        setErrorMessage(errorText);
        return;
      }

      const { token, userId } = await response.json();
      await AsyncStorage.setItem('token', token);
      await AsyncStorage.setItem('userID', userId);
      setUserToken(token);
      setErrorMessage('');
      navigation.navigate('Home');
      
    } catch (error) {
      console.error('Network error:', error);
      setErrorMessage('Network error. Please try again later.');
    }
  }

  
  
  

  return (
    <View style={tailwind('p-4')}>
            {errorMessage ? <Text style={tailwind('text-red-500 mb-2 text-center')}>{errorMessage}</Text> : null}
      <TextInput
        style={tailwind('border border-gray-500 p-2 mb-4')}
        value={username}
        onChangeText={setUsername}
        placeholder="Username"
      />
      <TextInput
        style={tailwind('border border-gray-500 p-2 mb-4')}
        value={password}
        onChangeText={setPassword}
        placeholder="Password"
        secureTextEntry
        required
      />
      <Button title="Log in" onPress={loginUser} />
      <Button title="Sign up instead" onPress={() => navigation.navigate('Signup')} />
    </View>
  );
}

export default LoginScreen;
