<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	// 👇 Verifica la ruta de tu archivo TS
	import {
		createMultiCurrencyType,
		updateMultiCurrencyType,
		type MultiCurrencyType
	} from '$lib/api/dashboard/a76/general_catalogs/multi-currency-types';
	import { companyStore } from '$lib/stores/company.svelte';
	import { obtenerAtajosFormularioMonedas } from '$lib/config/shortcuts/dashboard/general_catalogs/multi_currency_types/edit';
	import { m } from '$lib/i18n/messages';

	let {
		open = $bindable(false),
		item = null,
		onSuccess
	}: {
		open: boolean;
		item?: MultiCurrencyType | null;
		onSuccess?: () => void;
	} = $props();

	// Atajos

	const isEdit = $derived(!!item);
	const title = $derived(
		isEdit ? m.multi_currency_edit_title() : m.multi_currency_new_title()
	);

	// Estado del formulario
	let formData = $state({
		currency_type_code: '',
		country_key: '',
		conversion_factor: null as number | null,
		date_str: '' // Usamos un string temporal para el input type="date"
	});

	let loading = $state(false);
	let error = $state<string | null>(null);

	// Cargar datos al abrir
	$effect(() => {
		if (open) {
			if (item) {
				// Truco: Convertir Entero (20251231) -> String ("2025-12-31")
				let dateFormatted = '';
				if (item.publication_date) {
					const s = item.publication_date.toString();
					if (s.length === 8) {
						dateFormatted = `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}`;
					}
				}

				formData = {
					currency_type_code: item.currency_type_code,
					country_key: item.country_key || '',
					conversion_factor: item.conversion_factor,
					date_str: dateFormatted
				};
			} else {
				// Default: Fecha de hoy
				formData = {
					currency_type_code: '',
					country_key: '',
					conversion_factor: null,
					date_str: new Date().toISOString().split('T')[0]
				};
			}
			error = null;
		}
	});

	async function handleSubmit() {
		loading = true;
		error = null;

		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) throw new Error(m.exchange_rate_error_no_company());

			// Validaciones
			if (!formData.currency_type_code.trim()) throw new Error(m.multi_currency_error_currency_required());
			if (!formData.date_str) throw new Error(m.multi_currency_error_date_required());

			// Truco: Convertir String ("2025-12-31") -> Entero (20251231)
			// Quitamos los guiones y parseamos a int
			const dateInt = parseInt(formData.date_str.replaceAll('-', ''), 10);

			// Preparar datos
			const dataToSend = {
				currency_type_code: formData.currency_type_code.trim().toUpperCase(),
				country_key: formData.country_key.trim().toUpperCase() || null,
				conversion_factor: formData.conversion_factor ? Number(formData.conversion_factor) : null,
				publication_date: dateInt // Mandamos el INT que espera Python
			};

			let response;
			if (isEdit && item) {
				response = await updateMultiCurrencyType(item.id, dataToSend, companyId);
			} else {
				response = await createMultiCurrencyType(dataToSend, companyId);
			}

			if (response?.error) {
				throw new Error(response.error);
			}

			open = false;
			if (onSuccess) onSuccess();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Error';
		} finally {
			loading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[500px]">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
		</Dialog.Header>

		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSubmit();
			}}
			class="space-y-4 py-4"
		>
			{#if error}
				<div class="rounded-md bg-destructive/15 p-3 text-sm text-destructive">
					{error}
				</div>
			{/if}

			<div class="grid gap-4">
				<div class="grid grid-cols-4 items-center gap-4">
					<Label for="currency_code" class="text-right"
						>{m.multi_currency_currency_label()} <span class="text-destructive">*</span></Label
					>
					<div class="col-span-3">
						<Input
							id="currency_code"
							bind:value={formData.currency_type_code}
							placeholder="{m.exchange_rate_example_suffix()} USD"
							maxlength={3}
							disabled={loading}
							required
						/>
						<p class="text-[10px] text-muted-foreground mt-1">{m.multi_currency_currency_help()}</p>
					</div>
				</div>

				<div class="grid grid-cols-4 items-center gap-4">
					<Label for="country_key" class="text-right">{m.multi_currency_country_label()}</Label>
					<div class="col-span-3">
						<Input
							id="country_key"
							bind:value={formData.country_key}
							placeholder="{m.exchange_rate_example_suffix()} MEX"
							maxlength={3}
							disabled={loading}
						/>
						<p class="text-[10px] text-muted-foreground mt-1">{m.multi_currency_country_help()}</p>
					</div>
				</div>

				<div class="grid grid-cols-4 items-center gap-4">
					<Label for="pub_date" class="text-right"
						>{m.multi_currency_date_label()} <span class="text-destructive">*</span></Label
					>
					<div class="col-span-3">
						<Input
							id="pub_date"
							type="date"
							bind:value={formData.date_str}
							disabled={loading}
							required
						/>
						<p class="text-[10px] text-muted-foreground mt-1">{m.multi_currency_date_help()}</p>
					</div>
				</div>

				<div class="grid grid-cols-4 items-center gap-4">
					<Label for="factor" class="text-right">{m.multi_currency_factor_label()}</Label>
					<div class="col-span-3">
						<Input
							id="factor"
							type="number"
							step="0.000001"
							bind:value={formData.conversion_factor}
							placeholder="0.000000"
							disabled={loading}
						/>
					</div>
				</div>
			</div>

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}>
					{m.exchange_rate_cancel()}
				</Button>
				<Button type="submit" disabled={loading}>
					{loading ? m.multi_currency_saving() : isEdit ? m.multi_currency_update() : m.multi_currency_create()}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>
