import React from 'react';

import { getAuth } from '@grund/auth-client';
import { RedirectAuth } from '@grund/react';

import { Wrapper, Button, Buttons, Form, Input } from './components';
import { useInputs, useMode } from './hooks';

function handleLogin(email: string, password: string) {
	const auth = getAuth();
	return auth.credentials?.login({ email, password });
}

function handleRegister(email: string, password: string) {
	const auth = getAuth();
	return auth.credentials?.register({ email, password });
}

export function AuthScreen() {
	const { isLogin, toggleMode, isLoading, setLoading } = useMode();
	const { email, password, setEmail, setPassword } = useInputs();

	async function handleSubmit(e: React.FormEvent) {
		e.preventDefault();

		// prettier-ignore
		const fn = isLogin
			? handleLogin
			: handleRegister;

		try {
			setLoading(true);
			await fn(email, password);
		} catch (err) {
			setLoading(false);
		}
	}

	const title = isLogin ? 'Sign in' : 'Register';
	const submitText = title;
	const toggleText = isLogin ? 'Register' : 'Sign in';

	return (
		<RedirectAuth to='/'>
			<Wrapper>
				<Form onSubmit={handleSubmit}>
					<h1>{title}</h1>

					<Input type='text' placeholder='Email' value={email} onValueChange={setEmail} />
					<Input type='password' placeholder='Password' value={password} onValueChange={setPassword} />

					<Buttons>
						<Button type='submit' loading={isLoading}>
							{submitText}
						</Button>
						<Button variant='tertiary' onClick={toggleMode}>
							{toggleText}
						</Button>
					</Buttons>
				</Form>
			</Wrapper>
		</RedirectAuth>
	);
}
