<svelte:head>
	<title>Generate your Image</title>
	<meta name="description" content="Svelte demo app" />
</svelte:head>

<script lang="ts">
	import { get } from "svelte/store";

	import Button from "$lib/components/Button.svelte";
	import Textarea from "$lib/components/fields/Textarea.svelte";
	import Banner from "$lib/components/generate/Banner.svelte";
	import Response from "$lib/components/generate/Response.svelte";
	import Autocomplete from "$lib/components/models/autocomplete/Autocomplete.svelte";
	import { generationStore } from "$lib/stores/use-generation";

	export let data
	let generation = get(generationStore);

	let loading: boolean = false;

	let form = ((data?.model?.id && generation?.form?.model?.id && data?.model?.id !== generation?.form?.model?.id) || !generation?.form) ? {
		model: data?.model ?? null,
		inputs: "",
		parameters: {
			negative_prompt: ""
		}
	} : generation?.form

	const handleSubmit = async () => {
		if (loading) return
    loading = true

		const request = await fetch(`/api/generate`, {
			method: "POST",
			headers: {
				"Content-Type": "application/json"
			},
			body: JSON.stringify(form)
		});

		const response = await request.json();

		generationStore.set({
			image: response?.image,
			gallery: response?.gallery,
			form: form
		})
    loading = false
	}
</script>

<main class="grid grid-cols-5 w-full h-full gap-5 xl:gap-10">
	<div class="w-full px-6 py-10 lg:px-10 lg:py-12 col-span-5 xl:col-span-3">
		<div class="w-full flex gap-8 flex-col-reverse xl:flex-col">
			<Banner />
			<h1 class="text-white font-semibold text-2xl">
				Start generating
			</h1>
		</div>
		<div class="mt-5 grid grid-cols-1 gap-6">
			<div>
				<p class="text-neutral-300 mb-2.5 text-base">Models</p>
				<Autocomplete
					value={form?.model}
					defaultModels={data?.models?.cards}
					onChange={(model) => form.model = model}
				/>
			</div>
			<div>
				<p class="text-neutral-300 mb-2.5 text-base">Prompt</p>
				<Textarea
					value={form?.inputs}
					placeholder="Aerial photography of a desert through autumn forests, with vibrant red and orange foliage"
					onChange={(inputs) => form.inputs = inputs}
				/>
			</div>
			<div>
				<p class="text-neutral-300 mb-2.5 text-base">Negative Prompt</p>
				<Textarea
					value={form?.parameters?.negative_prompt}
					placeholder="Write your negative prompt here"
					onChange={(negative_prompt) => form.parameters.negative_prompt = negative_prompt}
				/>
			</div>
			<div class="flex justify-end">
				<Button
					icon="fluent:glance-horizontal-sparkles-16-filled"
					theme="pink"
					size="lg"
					{loading}
					onClick={handleSubmit}
				>
					Generate
				</Button>
			</div>
		</div>
	</div>
	<Response loading_generation={loading} />
</main>