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

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

  const tailwind = useTailwind();


async function signupUser() {
  try {
    const apiUrl = await AsyncStorage.getItem('apiEndpoint')
    setErrorMessage(null); // Reset the error message before starting a new request
    const response = await fetch(`${apiUrl}/api/v1/app/auth/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
    });

    if (!response.ok) {
      throw new Error(`Failed to signup: ${response.status} ${await response.text()}`);
    }

    const { token, userId } = await response.json();
    await AsyncStorage.setItem('token', token);
    await AsyncStorage.setItem('userID', userId);
    navigation.reset({
      index: 0,
      routes: [{ name: 'Home' }],
    });
  } catch (error) {
    console.error('Error:', error);
    setErrorMessage(error.message);
  }
}


  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
      />
      <Button title="Sign up" onPress={signupUser} />
      <Button title="Log in instead" onPress={() => navigation.navigate('Login')} />
    </View>
  );
}

export default SignupScreen;
