<script lang="ts">
	import { untrack } from "svelte";
	import { page } from "$app/state";
	import { resolve } from "$app/paths";
	import { getAuth } from "$lib/auth.svelte";
	import { createBobbinClient } from "$lib/api/client";
	import RepoCard from "$lib/components/repo/RepoCard.svelte";
	import Section from "$lib/components/ui/Section.svelte";
	import Pagination from "$lib/components/ui/Pagination.svelte";
	import Error from "$lib/components/ui/Error.svelte";
	import { createCursorPager, discoveredPageCount, pageCount } from "../pagination.svelte";
	import { PROFILE_PAGE_LIMIT, fetchReposPage } from "../pages";
	import { repoKey, type RepoCardData } from "../types";
	import Search from "$icon/search";
	import X from "$icon/x";

	interface Props {
		initial: RepoCardData[];
		cursor?: string;
		total: number;
		did: string;
		handle: string;
	}

	let { initial, cursor: initialCursor, total, did, handle }: Props = $props();

	const auth = getAuth();

	let searchQuery = $derived(page.url.searchParams.get("q") ?? "");
	const pager = createCursorPager(
		{ items: untrack(() => initial), cursor: untrack(() => initialCursor) },
		(cursor) => {
			const ctx = createBobbinClient({ serviceUrl: auth.bobbinUrl });
			return fetchReposPage(ctx, {
				did,
				handle,
				viewerDid: auth.currentDid ?? undefined,
				q: searchQuery || undefined,
				cursor
			});
		}
	);
	const repos = $derived(pager.items);
	const pages = $derived(
		searchQuery
			? discoveredPageCount(pager.state.page, pager.hasNext)
			: pageCount(total, PROFILE_PAGE_LIMIT)
	);
</script>

<Section
	empty={repos.length === 0}
	emptyMessage={searchQuery ? `No repositories match "${searchQuery}".` : "No repositories found."}
>
	{#snippet header()}
		<div class="mb-4">
			<form class="relative flex" method="GET">
				<input type="hidden" name="tab" value="repos" />
				<div class="relative flex flex-1">
					<input
						class="peer flex-1 rounded-l border border-border-default bg-background-default py-1.5 pr-10 pl-3 outline-none focus:border-border-strong focus:ring-1 focus:ring-border-strong"
						type="text"
						name="q"
						value={searchQuery}
						placeholder="Search repositories..."
					/>
					<a
						href={resolve(`${page.url.pathname}?tab=repos` as "/")}
						class="absolute top-1/2 right-3 hidden -translate-y-1/2 text-foreground-subtle peer-not-placeholder-shown:block hover:text-foreground-default"
					>
						<X class="size-4" />
					</a>
				</div>
				<button
					type="submit"
					class="rounded-r border border-l-0 border-border-default bg-background-default p-2 text-foreground-subtle hover:bg-background-subtle hover:text-foreground-default"
				>
					<Search class="size-4" />
				</button>
			</form>
		</div>
	{/snippet}
	{#each repos as repo (repoKey(repo))}
		<RepoCard {repo} showOwner={false} />
	{/each}
	{#snippet footer()}
		{#if pages > 1}
			<div class="mt-4 flex justify-center">
				<Pagination
					page={pager.state.page}
					total={pages}
					labels
					disabled={pager.state.kind === "loading"}
					onchange={pager.select}
					class="gap-5"
				/>
			</div>
		{/if}
		{#if pager.state.kind === "failed"}
			<Error label="couldn't load that page. try again." class="mt-2" />
		{/if}
	{/snippet}
</Section>
