import { component$, useVisibleTask$ } from "@builder.io/qwik";
import { routeLoader$, type DocumentHead } from "@builder.io/qwik-city";
import Controlbar from "~/components/dashboard/Controlbar";
// import Dropzone from "~/components/Dropzone";
import File from "~/components/dashboard/File";
import { SolarUploadLinear, SvgSpinnersBarsRotateFade } from "~/components/misc/Icons";
import { useNanostore$ } from "~/hooks/nanostores";
import { api } from "~/lib/api";
import { areFilesLoaded, dashboardFiles } from "~/lib/stores";
import { StereoFile } from "~/lib/types";

export const useAuthCheck = routeLoader$(({ cookie, redirect: r }) => {
	const jwt = cookie.get("jwt");
	if (jwt) return {};
	throw r(302, "/");
});

export default component$(() => {
	const files = useNanostore$<StereoFile[]>(dashboardFiles);
	const loaded = useNanostore$<boolean>(areFilesLoaded);

	useVisibleTask$(async () => {
		loaded.value = false;
		files.value = await api.list();
		console.log("Files loaded:", files.value);
		loaded.value = true;
	});

	return (
		<>
			{/* <Dropzone /> */}
			<Controlbar />
				{!loaded.value ? (
					<div class="absolute w-full h-screen flex justify-center items-center flex-col">
						<p class="text-gray-500 text-8xl font-bold"><SvgSpinnersBarsRotateFade /></p>
						<p class="text-gray-700 text-2xl font-light italic">loading your files...</p>
						<span class="text-gray-700 text-lg font-light flex gap-[0.5ch] items-center">please wait... <span class="animate-spin">⏳</span></span>
					</div>
				) : (
					files.value.length === 0 ? (
						<div class="absolute w-full h-screen flex justify-center items-center flex-col">
							<p class="text-gray-500 text-8xl font-bold">{
								[
									"┻━┻︵ \\(°□°)/ ︵ ┻━┻",
									"┻━┻︵ヽ(`Д´)ﾉ︵ ┻━┻",
									"ʕノ•ᴥ•ʔノ ︵ ┻━┻",
									"(╯°Д°）╯︵ /(.□ . \\)",
									"┬─┬﻿ ︵ /(.□. \\）",
									"(/ .□.)\\ ︵╰(゜Д゜)╯︵ /(.□. \\)"
								].sort(() => Math.random() - 0.5)[0]
							}</p>
							<p class="text-gray-700 text-2xl font-light italic">you haven't uploaded any files yet!</p>
							<span class="text-gray-700 text-lg font-light flex gap-[0.5ch] items-center">click the <span class="animate-bounce p-0.5 bg-gray-500 rounded-sm"><SolarUploadLinear /></span> button to get started</span>
						</div>
					)
					: (
						<div class="grid xl:grid-cols-4 md:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-3 p-6 mb-14">
							{files.value.map((file) => (
								<File key={file.Name} file={file} />
							))}
						</div>
					)
				)}

		</>
	);
});

export const head: DocumentHead = {
	title: "Welcome to Qwik",
	meta: [
		{
			name: "description",
			content: "Qwik site description",
		},
	],
};
