import { Link, useParams } from "react-router-dom"
import { useEffect, useState } from "react";
import { DbRelease } from "../server/dbal/dbal";
import { css } from "@emotion/css";

type Info = {
    author: string | null;
    games: {slug: string; releases: DbRelease[]}[];
}

export const AuthorPage = () => {
	const {author} = useParams();
	const [info, setInfo] = useState<Info | null>(null);

	useEffect(() => {
		const fetchInfo = async () => {
			let url = `/api/author?author=${author}`;
			const information = await fetch(url);
			const json = await information.json();
			console.log('json', json);
			setInfo(json);
		}
		fetchInfo();
	}, [setInfo, author]);

	if (!info) {
		return (
			<div>
				LOADING...
			</div>
		)
	}

	if (!info.author) {
		return (
			<div>
				NOT FOUND
			</div>
		)
	}

	return (
		<div className={css`
			margin: auto;
			width: max-content;
			max-inline-size: 66ch;
			padding: 1.5em;
			display: flex;
			flex-direction: column;
			gap: 1em;
		`}>
			<h1>{author}</h1>
			{
				info.games.map(game => (
					<Link key={game.slug} to={`/u/${author}/${game.slug}`}>
						<h3>{game.releases[0].manifest.title ?? game.slug}</h3>
					</Link>
				))
			}
		</div>
	)
}