import clsx from 'clsx';
import { A, useNavigate } from '@solidjs/router';
import { createQuery } from '@tanstack/solid-query';
import { For, Show, createMemo, createSignal, type Component } from 'solid-js';

import { LoadingState, buttonStyles, cardStyles, inputStyles } from '../components/common';
import { resolveActor } from '../lib/api/identity';
import { listRepoRecords } from '../lib/api/repos';
import { useAuth } from '../lib/auth';
import { formatRelativeTime, loadRecentRepos, parseRepoJump } from '../lib/repo-utils';

const SAMPLE_REPOS = [
	{ owner: 'mary.my.id', slug: 'atcute' },
	{ owner: 'mary.my.id', slug: 'boat' },
	{ owner: 'mary.my.id', slug: 'aglais' },
];

export const HomePage: Component = () => {
	const auth = useAuth();
	const [jump, setJump] = createSignal('');
	const recentRepos = createMemo(loadRecentRepos);
	const navigate = useNavigate();

	const ownReposQuery = createQuery(() => ({
		queryKey: ['own-repos', auth.currentDid()],
		enabled: Boolean(auth.currentDid()),
		queryFn: async () => {
			const actor = await resolveActor(auth.currentDid()!);
			return listRepoRecords(actor);
		},
	}));

	const onSubmit = (event: SubmitEvent) => {
		event.preventDefault();
		const parsed = parseRepoJump(jump());
		if (!parsed) {
			return;
		}

		navigate(`/${parsed.owner}/${parsed.repo}`);
	};

	return (
		<div class="untangled-home-grid">
			<div class="flex flex-col gap-4">
				<div class={cardStyles('p-6')}>
					<div class="flex items-center gap-3 mb-6">
						<img src="/static/logos/dolly.svg" alt="" class="size-12" />
						<div>
							<h1 class="text-2xl font-bold m-0">untangled</h1>
							<p class="m-0 text-sm text-gray-500 dark:text-gray-400">tightly-knit social coding</p>
						</div>
					</div>

					<form onSubmit={onSubmit} class="flex flex-col gap-3">
						<label class="text-sm font-medium">repository</label>
						<div class="flex gap-2">
							<input
								value={jump()}
								onInput={(event) => setJump(event.currentTarget.value)}
								placeholder="mary.my.id/atcute"
								class={inputStyles()}
							/>
							<button type="submit" class={clsx(buttonStyles('primary'), 'shrink-0')}>
								open
							</button>
						</div>
					</form>

					<div class="mt-8">
						<div class="text-sm font-medium mb-3">sample repositories</div>
						<div class="grid gap-2 sm:grid-cols-2">
							<For each={SAMPLE_REPOS}>
								{(repo) => (
									<A href={`/${repo.owner}/${repo.slug}`} class={cardStyles('p-4 hover:bg-gray-50 dark:hover:bg-gray-700/30 no-underline')}>
										<div class="font-medium">
											{repo.owner}/{repo.slug}
										</div>
									</A>
								)}
							</For>
						</div>
					</div>
				</div>
			</div>

			<div class="flex flex-col gap-4">
				<div class={cardStyles('p-6')}>
					<div class="text-sm font-medium mb-3">recent</div>
					<Show
						when={recentRepos().length > 0}
						fallback={<div class="text-sm text-gray-500 dark:text-gray-400">No recent repositories.</div>}
					>
						<div class="flex flex-col gap-2">
							<For each={recentRepos()}>
								{(repo) => (
									<A href={`/${repo.owner}/${repo.slug}`} class="no-underline hover:no-underline rounded border border-gray-200 dark:border-gray-700 px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-700/30">
										<div class="font-medium">{repo.title}</div>
										<div class="text-xs text-gray-500 dark:text-gray-400">{formatRelativeTime(repo.updatedAt)}</div>
									</A>
								)}
							</For>
						</div>
					</Show>
				</div>

				<Show when={auth.currentDid()}>
					<div class={cardStyles('p-6')}>
						<div class="text-sm font-medium mb-3">your repositories</div>
						<Show
							when={!ownReposQuery.isLoading}
							fallback={<LoadingState label="Loading repositories..." />}
						>
							<div class="flex flex-col gap-2">
								<For each={ownReposQuery.data ?? []}>
									{(repo) => (
										<A
											href={`/${auth.currentDid()}/${repo.value.name?.trim() || repo.rkey}`}
											class="no-underline hover:no-underline rounded border border-gray-200 dark:border-gray-700 px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-700/30"
										>
											<div class="font-medium">{repo.value.name?.trim() || repo.rkey}</div>
											<div class="text-xs text-gray-500 dark:text-gray-400">
												{repo.value.description || repo.value.repoDid}
											</div>
										</A>
									)}
								</For>
							</div>
						</Show>
					</div>
				</Show>
			</div>
		</div>
	);
};
