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

export default function Login({ navigation }) {
	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: token });
				}
			}
		});
		return unsubscribe;
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	console.log(authHeader.value);

	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 />
						<Button
							color="orange"
							title="Go to app"
							onPress={() => navigation.push("Tabs")}
						/>
					</>
				)}
			</View>
		</TouchableWithoutFeedback>
	);
}
