import type { Metadata, ResolvingMetadata } from 'next';
import Image from 'next/image';

import DownloadTTY from './download_tty';
import Content from './content';
import * as style from './page.css';
import download_image_dark from './download_dark.svg';
import download_image_light from './download_light.svg';

type SearchParams = { [key: string]: string | string[] | undefined };

type Props = {
	params: { file: string },
	searchParams: SearchParams,
};

function get_path(file: string[]) {
	return file.join("/");
}

function get_root(search_params: SearchParams) {
	return search_params['root'] ?? 'raw.monodon.me';
}

export async function generateMetadata(
	{ params, searchParams }: Props,
	parent: ResolvingMetadata,
): Promise<Metadata> {
	return {
		title: `${get_path(params.file)} | ${get_root(searchParams)}`,
	};
}

export default async function Page({
	params, searchParams
}: Props) {
	const path = get_path(params.file);
	const root = `https://${get_root(searchParams)}/`;
	const full = `${root}${path}`;

	const download_ttys = [
		`curl -O ${root}${path}`,
		`wget ${root}${path}`,
	];

	return (
		<div className={style.root}>
			<div className={style.center}>
				<div className={style.title_group}>
					<div className={style.title_text_group}>
		 				<p className={style.supertitle}>{root}</p>
						<p className={style.title}>{path}</p>
					</div>
					<button className={style.download_button}>
						<a className={style.download_link} href={full} download>
							<Image
								className={style.download_button_image_dark}
								src={download_image_dark}
								alt="Download Button"
							/>
							<Image
								className={style.download_button_image_light}
								src={download_image_light}
								alt="Download Button"
							/>
						</a>
					</button>
				</div>
				<div className={style.download_tty_group}>
					{download_ttys.map((text, index) => <DownloadTTY key={index} text={text} />)}
				</div>
				<Content src={`${root}${path}`} />
			</div>
		</div>
	);
}
