<script lang="ts">
	import { onMount } from 'svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import { uiStore } from '$lib/stores/ui.svelte';
	import { getExchangeRates } from '$lib/api/dashboard/a76/general_catalogs/exchange-rate';
	import CreateEditDialog from './create-edit-dialog.svelte';

	let {
		overlayClass = 'bg-black/5'
	}: {
		overlayClass?: string;
	} = $props();

	let open = $state(false);
	let checked = $state(false);

	async function checkExchangeRate() {
		if (!companyStore.activeCompany?.id) {
			return;
		}

		// Use local date instead of UTC
		const today = new Date().toLocaleDateString('fr-CA'); // YYYY-MM-DD

		try {
			const response = await getExchangeRates(companyStore.activeCompany.id, {
				date: today,
				page_size: 1
			});

			// api.get returns { data: ..., status: ... } and types now reflect that
			const items = response.data?.items || [];

			if (items.length === 0) {
				if (!uiStore.isExchangeRateDialogOpen) {
					uiStore.isExchangeRateDialogOpen = true;
					open = true;
				}
			}
		} catch (error) {
			console.error('[ExchangeRateGuard] Error checking exchange rate:', error);
		} finally {
			checked = true;
		}
	}

	$effect(() => {
		if (companyStore.activeCompany?.id && !checked) {
			checkExchangeRate();
		}
	});

	function handleSuccess() {
		uiStore.isExchangeRateDialogOpen = false;
		checked = true;
	}

	$effect(() => {
		// Sincronizar el estado global con el estado local
		if (open) {
			uiStore.isExchangeRateDialogOpen = true;
		} else if (checked) {
			// Solo limpiar si este componente ya hizo su check inicial
			// y el estado local es cerrado.
			if (uiStore.isExchangeRateDialogOpen && !open) {
				uiStore.isExchangeRateDialogOpen = false;
			}
		}
	});
</script>

<CreateEditDialog bind:open onSuccess={handleSuccess} {overlayClass} />
