// Login.tsx
import React, { useEffect, useState } from 'react';
import {
	Button,
	Keyboard,
	Text,
	TextInput,
	TouchableWithoutFeedback,
	View,
} from 'react-native';
import { handleSignInWithPhoneNumber, confirmCode, onAuthStateChanged } from '../auth';
import { FirebaseAuthTypes } from '@react-native-firebase/auth';
import { useAuthHeader } from '../graphql/client';
import AsyncStorage from '@react-native-async-storage/async-storage';
import SignOutButton from '../component/buttons/sign-out';

export default function Login() {
	const [phoneNumber, setPhoneNumber] = useState<string>('');
	const [code, setCode] = useState<string>('');
	const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);
	const [confirm, setConfirm] = useState<FirebaseAuthTypes.ConfirmationResult | null>(null);
	const { authHeader, setAuthHeader } = useAuthHeader()

	useEffect(() => {
		const unsubscribe = onAuthStateChanged(async (user) => {
			setUser(user)
			if (user) {
				const token = await user.getIdToken()
				if (token) {
					await AsyncStorage.setItem('token', token);
					setAuthHeader({ key: "Authorization", value: `Bearer ${token}` });
				}
			}
		});
		return unsubscribe;
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);



	return (
		<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
			<View style={{ alignItems: 'center' }}>
				<TextInput
					style={{
						width: "50%",
						height: 30,
						borderWidth: 1,
						borderColor: "black",
						marginBottom: 20,
					}}
					placeholder="Phone"
					textContentType="telephoneNumber"
					keyboardType="phone-pad"
					autoCapitalize="none"
					value={phoneNumber}
					onChangeText={(value) => setPhoneNumber(value)}
				/>
				{confirm && (
					<TextInput
						style={{
							width: "50%",
							height: 30,
							borderWidth: 1,
							borderColor: "black",
							marginBottom: 20,
						}}
						placeholder="Code"
						keyboardType="number-pad"
						textContentType="oneTimeCode"
						autoCapitalize="none"
						value={code}
						onChangeText={(value) => setCode(value)}
					/>
				)}
				<Button
					title={!confirm ? 'Receive code' : 'Confirm code'}
					onPress={() => !confirm ? handleSignInWithPhoneNumber(phoneNumber).then(setConfirm) : confirm && confirmCode(confirm, code)}
				/>
				<Text>{authHeader.key}: {authHeader.value}</Text>
				{user && (
					<>
						<Text style={{ marginTop: 10 }}>
							Display name: {user?.displayName}
						</Text>
						<Text>Phone number: {user?.phoneNumber}</Text>

						<SignOutButton />
					</>
				)}
			</View>
		</TouchableWithoutFeedback>
	);
}
