import { createMemo, createSignal, onMount, type Component } from "solid-js";
import appData from "@/data/apps.toml";
import Fuse, { type IFuseOptions } from "fuse.js";

interface App {
	name: string;
	url: string;
	flathub: string;
}

interface Task {
	name: string;
	key: string;
	apps: App[];
}

const fuseOptions: IFuseOptions<Task> = {
	keys: ["name", "apps.name"],
	threshold: 0.5,
	shouldSort: true,
};

const AppList: Component<{ lang: string }> = ({ lang }) => {
	const [currentPlaceholder, setCurrentPlaceholder] = createSignal("");
	const [searchQuery, setSearchQuery] = createSignal("");
	const [flathub, setFlathub] = createSignal(false);
	const fuse = new Fuse(appData.tasks as Task[], fuseOptions);
	const searchResults = createMemo(() => {
		if (searchQuery().trim() === "") {
			return appData.tasks.map((task) => ({ item: task }));
		}

		return fuse.search(searchQuery());
	});
	const [strings, setStrings] = createSignal({
		todo: "I need to do...",
		categories: {} as Record<string, string>,
	});

	onMount(async () => {
		setCurrentPlaceholder(
			appData.tasks[Math.floor(Math.random() * appData.tasks.length)]
				.name,
		);
		setInterval(() => {
			const cats = Object.values(strings().categories);

			setCurrentPlaceholder(
				cats[Math.floor(Math.random() * cats.length)],
			);
		}, 3000);

		setStrings(
			(await import(`@/data/strings/${lang}.toml`)).default.appList,
		);

		if (lang === "en") return;

		fuse.setCollection(
			(appData.tasks as Task[]).map((task) => ({
				...task,
				name: strings().categories[task.key] ?? task.name,
			})),
		);
	});

	function getTaskName(key: string) {
		return strings().categories[key];
	}

	return (
		<>
			<div
				id="searchBox"
				class="mt-4 mb-2 flex justify-center items-center"
			>
				<span>{strings().todo}</span>
				<input
					type="search"
					name="taskSearch"
					id="taskSearch"
					placeholder={currentPlaceholder()}
					value={searchQuery()}
					oninput={(e) => setSearchQuery(e.currentTarget.value)}
					class="ml-4 px-4 py-2 border rounded dark:border-slate-600 border-gray-400"
				/>
			</div>
			<div class="mb-4 flex justify-center items-center gap-2">
				<input
					type="checkbox"
					id="flathub"
					checked={flathub()}
					oninput={(e) => setFlathub(e.target.checked)}
				/>
				<label>Link to Flathub (if available)</label>
			</div>
			<div
				id="appList"
				class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"
				role="list"
			>
				{searchResults().map(({ item }) => (
					<li class="p-4 border rounded dark:border-slate-600 border-gray-400 flex">
						<div class="font-bold border-r dark:border-slate-600 border-gray-400 w-[30%] pr-4 mr-4">
							{getTaskName(item.key) ?? item.name}
						</div>
						<ul class="flex gap-x-4 flex-wrap">
							{item.apps.map((app) => (
								<li>
									<a
										href={
											flathub()
												? (app.flathub ?? app.url)
												: app.url
										}
										target="_blank"
										rel="noopener"
									>
										{app.name}
									</a>
								</li>
							))}
						</ul>
					</li>
				))}
			</div>
		</>
	);
};

export default AppList;
