import { useEffect, useState } from 'preact/hooks';

type EntryBody = {
	err: boolean;
	referral: string;
	key: string;
}


export const Home = () => {
	const [referral, setReferral] = useState('');
	const [entryBody, setEntryBody] = useState<EntryBody | null>({
		err: true,
		referral: '',
		key: ''
	});

	useEffect(() => {
		console.log('Referral:', referral);
	}, [referral]);

	const entry = async () => {
		let res = await fetch("http://localhost:8080/entry", { 
			method: 'GET',
			headers: { referral }
		})
		
		if (!res.ok) {
			console.error('Error:', res.status);
			return
		}

		let body: EntryBody = await res.json();

		if (body.err) {
			console.error('Error:', body.referral);
			window.location.href = '/error';

			return
		}

		console.log('Entry:', body);
		
		setEntryBody(body);

		setReferral('');
	}
	
	return (
		<div class="flex flex-col gap-6 w-full h-full justify-center items-center">
			<h1 class="text-6xl font-bold animate-pulse">???</h1>
			<div class="flex flex-col justify-center items-center gap-4">
				<span>
					<p class="opacity-100 hover:opacity-75 transition-opacity">
						Referral:
					</p>
					
				
					<div class="flex gap-2">
						<input
							type="text"
							value={referral}
							onInput={(e) => setReferral(e.currentTarget.value)}

							class="bg-black text-green-500 border-green-500 border-2 px-2 hover:bg-green-500 hover:text-black active:bg-green-500 active:text-black transition-colors"
						/>

						<button
							onClick={async () => await entry()}
							class="bg-green-500 text-black hover:bg-black hover:text-green-500 transition-colors px-4"
						>
							Submit
						</button>
					</div>
				</span>

				<div>
					{
						!entryBody.err && (
							<>
								<h2>Key: {entryBody?.key}</h2>
								<h2>Referral: {entryBody?.referral}</h2>
							</>
						)
					}
				</div>

				<div class="w-2/3 text-center flex flex-col gap-2">
					<div>
						<b>What is this?</b>
						<p>At exactly 00:00 CET on 1 Jan, the system will choose a random entry. Their referral key shall be publically
							displayed on this page. The person associated to this referral key shall contact us with their private key.
							They shall win a little prize. To have one's entry weigh more than the rest, one shall have to spread their
							referral key amongst the people. Every referral shall increase their chance of getting selected.
						</p>
					</div>

					<div>
						<b>How does one enter?</b>
						<p>One needs a referral key to enter.</p>
					</div>
				</div>
			</div>
		</div>
	)
};