<script lang="ts">
	import { X } from '@lucide/svelte';
	import { scale } from 'svelte/transition';
	import { backOut } from 'svelte/easing';
	import { Button } from '$lib/components/ui/button';
	import { billingModalState } from '$lib/state/billing-modal.svelte';
	import { authState } from '$lib/state/auth.svelte';

	let { error = $bindable() } = $props();
	let showAlert = $state(false);

	$effect(() => {
		if (error.size > 0) {
			showAlert = true;
			// const timer = setTimeout(() => (showAlert = false), 6_000);
			// return () => clearTimeout(timer);
		} else {
			showAlert = false;
		}
	});
</script>

{#if showAlert}
	<div
		class="mb-2.5"
		transition:scale={{ duration: 250, easing: backOut, start: 1.02 }}
		onoutroend={() => (error = new Set())}
	>
		<div
			class="relative inline-flex w-fit items-center gap-1.5 rounded-t-2xl bg-rose-500/10 pt-3 pr-5 pl-4 text-[11px] font-semibold text-rose-600 uppercase"
		>
			<button
				class="flex size-3 -translate-y-[0.5px] cursor-pointer items-center justify-center rounded-full bg-rose-600 text-white hover:bg-rose-600/80"
				onclick={() => (error = new Set())}
			>
				<X class="size-2.5" />
			</button>
			Error
			<div
				class="absolute -right-3.5 bottom-0 h-3.5 w-3.5"
				style="background: radial-gradient(circle at top right, transparent 14px, rgb(244 63 94 / 0.1) 14px)"
			></div>
		</div>
		<div
			class="-translate-y-[3px] rounded-r-2xl rounded-b-xl bg-rose-500/10 px-4 py-3 text-xs whitespace-pre-line text-rose-500"
		>
			{#each error as err (err)}
				{err}
				{#if err.includes('is not supported by any provider')}
					<a
						target="_blank"
						href="https://huggingface.co/settings/inference-providers/settings"
						class="mt-2 block"
					>
						<Button variant="outline" size="3xs">View supported providers</Button>
					</a>
				{:else if err.includes('exceeded your monthly included credits') || err.includes('reached the free monthly usage limit') || err.includes('Credit balance is depleted')}
					<div class="mt-2 flex items-center gap-1">
						<a target="_blank" href="https://huggingface.co/settings/billing">
							<Button variant="outline" size="3xs">Upgrade your plan</Button>
						</a>
						{#if (authState.user?.orgs?.length ?? 0) > 0}
							<Button variant="outline" size="3xs" onclick={() => (billingModalState.open = true)}
								>Update your billing information</Button
							>
						{/if}
					</div>
				{:else if err.includes('to call Inference Providers on behalf of org')}
					<Button
						variant="outline"
						size="3xs"
						onclick={() => (billingModalState.open = true)}
						class="mt-2 block">Change billing option</Button
					>
				{/if}
			{/each}
		</div>
	</div>
{/if}
