import React, { useState } from 'react';
import { View, TextInput, Button, StyleSheet } from 'react-native';
import { signInWithEmailAndPassword, createUserWithEmailAndPassword } from 'firebase/auth';
import { auth } from '../config/firebase';
import { useDispatch } from 'react-redux';
import { setUser } from '../store/authSlice';

function LoginScreen({ navigation }: any) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const dispatch = useDispatch();

  const handleLogin = async () => {
    try {
      const userCredential = await signInWithEmailAndPassword(auth, email, password);
      dispatch(setUser({ uid: userCredential.user.uid, email: userCredential.user.email! }));
      navigation.replace('Projects');
    } catch (error: any) {
      alert(error.message);
    }
  };

  const handleRegister = async () => {
    try {
      const userCredential = await createUserWithEmailAndPassword(auth, email, password);
      dispatch(setUser({ uid: userCredential.user.uid, email: userCredential.user.email! }));
      navigation.replace('Projects');
    } catch (error: any) {
      alert(error.message);
    }
  };

  return (
    <View style={styles.container}>
      <TextInput style={styles.input} placeholder="Email" value={email} onChangeText={setEmail} />
      <TextInput style={styles.input} placeholder="Jelszó" value={password} onChangeText={setPassword} secureTextEntry />
      <Button title="Bejelentkezés" onPress={handleLogin} color="#ff00ff" />
      <Button title="Regisztráció" onPress={handleRegister} color="#ff00ff" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, justifyContent: 'center', backgroundColor: '#000000' },
  input: { borderWidth: 1, borderColor: '#333333', padding: 8, marginBottom: 16, borderRadius: 4, backgroundColor: '#1a1a1a', color: '#ffffff' },
});

export default LoginScreen;
