<script lang="ts">
	import SImage from './SImage.svelte';
	import InfiniteLoading from './InfiniteLoading.svelte';
	import Masonry from './Masonry.svelte';
	import type { AppImageResponse } from '../types';

	interface Props {
		fetchData: (queryParams: any) => Promise<any>;
		flagReload?: any;
		isMasonary?: boolean;
		onChange?: (image: AppImageResponse) => void;
	}

	let { fetchData, flagReload = {}, isMasonary = true, onChange }: Props = $props();
	let imageList: AppImageResponse[] = $state([]);
	let nextParams: any = $state(null);
	let lastFlag: any = $state(flagReload);

	$effect(() => {
		if (lastFlag != flagReload && imageList.length != 0) {
			lastFlag = flagReload;
			nextParams = null;
			imageList = [];
		}
	});

	export const reload = () => {
		imageList = [];
		nextParams = null;
		load();
	};
	function selectImage(image: any) {
		onChange?.(image);
	}

	async function load() {
		const data = await fetchData(nextParams);
		imageList = imageList.concat(data.data);
		nextParams = data.nextParams;
		if (data.data?.length > 0) {
			return true;
		}
		return false;
	}

	async function infiniteHandler({ loaded, complete }: any) {
		if (await load()) {
			loaded();
		} else {
			complete();
		}
	}
</script>

{#if isMasonary}
	<div class="flex overflow-y-auto overflow-x-hidden flex-col w-full h-full">
		<Masonry items={imageList} onSelect={(v) => selectImage(v)} />

		<div class="w-full h-2">
			<InfiniteLoading onInfinite={infiniteHandler} identifier={flagReload} distance={400} />
		</div>
	</div>
{:else}
	<div class="flex overflow-y-auto overflow-x-hidden flex-col w-full h-full">
		<div class="grid grid-cols-2 gap-2">
			{#each imageList as image}
				<button class="rounded shadow w-ful" onclick={() => selectImage(image)}>
					<SImage class="w-full h-full" src={image.src} alt={image.alt ?? 'image media'} />
				</button>
			{/each}
		</div>

		<div class="w-full h-2">
			<InfiniteLoading onInfinite={infiniteHandler} identifier={flagReload}>
				{#snippet noResults()}
					<div class="mt-10 flex-center">...</div>
				{/snippet}
				{#snippet noMore()}
					<div class="mt-10 flex-center">...</div>
				{/snippet}
			</InfiniteLoading>
		</div>
	</div>
{/if}
