<template>
	<div class="py-24">
		<main class="container mx-auto">
			<section
				class="py-24 rounded-3xl border-primary border max-w-screen-2xl"
				:class="cardClass"
				:style="cardStyle"
			>
				<div
					class="flex flex-col items-center justify-center"
					v-if="!submitted"
				>
					<h2 class="text-4xl font-bold text-center text-primary">
						{{ heading }}
					</h2>
					<p class="mt-4 text-center text-gray-800 dark:text-gray-100">
						{{ subheading }}
					</p>
					<UForm
						class="mt-8 flex flex-col items-center justify-center w-full max-w-lg"
						:schema="schema"
						:state="state"
						@submit="onSubmit"
					>
						<div class="w-full text-center">
							<UFormField label="" name="email" class="w-full">
								<UInput
									padded
									placeholder="Enter your email"
									icon="i-lucide-mail"
									size="xl"
									class="w-full flex-1"
									v-model="state.email"
									:loading="loading"
									:disabled="disabled"
								/>
							</UFormField>
							<UButton
								type="submit"
								size="xl"
								class="mt-6"
								:label="submitLabel"
							/>
						</div>
					</UForm>
				</div>
				<div class="text-center text-2xl" v-else>
					<div class="text-3xl font-bold">Done!</div>
					You have successfully subscribed.
				</div>
			</section>
		</main>
	</div>
</template>

<script setup>
import { z } from "zod";

const toast = useToast();
const props = defineProps({
	heading: {
		type: String,
		default: "Stay Up To Date",
	},
	subheading: {
		type: String,
		default: "Stay up to date with our latest news and product announcements.",
	},
	submitLabel: {
		type: String,
		default: "Subscribe",
	},
	cardClass: {
		type: String,
		default: `bg-fit bg-center bg-no-repeat bg-primary/5`,
	},
	cardStyle: {
		type: String,
		default: `background-image: url('https://cdn.x.enterprises/bg-subscription-poof2.webp');`,
	},
	organizationId: {
		type: String,
		required: true,
	},
	endpoint: {
		type: String,
		default: "https://api.emailmarketingnewsletters.com",
	},
});

const schema = z.object({
	email: z.string().email("Invalid email"),
});

const state = reactive({
	email: undefined,
});

async function onSubmit(event) {
	loading.value = true;
	disabled.value = true;
	try {
		await $fetch(`${props.endpoint}/public/subscriptions/subscribe`, {
			method: "POST",
			body: JSON.stringify({
				email: state.email,
				organizationId: props.organizationId,
			}),
		});
		submitted.value = true;
		toast.add({
			icon: "i-lucide-badge-check",
			title: "You have successfully subscribed to our newsletter.",
		});
	} catch (error) {
		console.log(error);
		toast.add({
			icon: "i-lucide-alert-circle",
			title: `An error occurred or you've already subscribed.`,
		});
	} finally {
		loading.value = false;
		disabled.value = false;
	}
}

const loading = ref(false);
const disabled = ref(false);
const submitted = ref(false);
</script>

