<script lang="ts">
	import { userHasExchangeRatesAction } from '$lib/permissions/catalogs/exchange-rates-permissions';

	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import * as Card from '$lib/components/ui/card';
	import { ArrowLeft } from 'lucide-svelte';
	import { createExchangeRate } from '$lib/api/dashboard/a76/general_catalogs/exchange-rate';
	import { companyStore } from '$lib/stores/company.svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosFormularioTiposCambio } from '$lib/config/shortcuts/dashboard/general_catalogs/exchange_rate/edit';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	let loading = $state(false);
	let error = $state<string | null>(null);
	const canCreate = $derived(userHasExchangeRatesAction($currentUser, 'create'));

	// Atajos
	useShortcuts(
		'Nuevo Tipo de Cambio',
		obtenerAtajosFormularioTiposCambio({
			manejarGuardar: () => {
				if (!canCreate) return;
				handleSubmit();
			},
			manejarCerrar: goBack
		})
	);

	let formData = $state({
		date: new Date().toISOString().split('T')[0], // Fecha de hoy
		value: null as number | null,
		local_currency: 'MXN',
		foreign_currency: 'USD'
	});

	async function handleSubmit() {
		if (!canCreate) {
			error = 'Permission denied: cat_exchange_rates.create';
			return;
		}
		loading = true;
		error = null;
		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) throw new Error('No hay una compañía seleccionada');

			if (!formData.date) throw new Error('La fecha es requerida');
			if (formData.value === null) throw new Error('El valor es requerido');

			const dataToSend = {
				date: formData.date,
				value: Number(formData.value),
				local_currency: formData.local_currency?.trim().toUpperCase() || null,
				foreign_currency: formData.foreign_currency?.trim().toUpperCase() || null
			};

			await createExchangeRate(dataToSend, companyId);

			// Éxito: Regresar a la lista
			goBack();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Error al guardar';
		} finally {
			loading = false;
		}
	}

	function goBack() {
		// Navegar un nivel arriba (a la lista)
		goto('/dashboard/general_catalogs/exchange-rate');
	}
</script>

<svelte:head>
	<title>Nuevo Tipo de Cambio - Anexo 76</title>
</svelte:head>

{#if !canCreate}
	<div class="p-6">
		<ErrorState status={403} error="Permission denied: cat_exchange_rates.create" />
	</div>
{:else}
<div class="max-w-2xl mx-auto space-y-6 p-4">
	<div class="flex items-center gap-4">
		<Button variant="ghost" size="icon" onclick={goBack}>
			<ArrowLeft class="h-4 w-4" />
		</Button>
		<div>
			<h1 class="text-2xl font-bold tracking-tight">Nuevo Tipo de Cambio</h1>
			<p class="text-muted-foreground">Registra un nuevo tipo de cambio en el sistema</p>
		</div>
	</div>

	<Card.Root>
		<Card.Content class="pt-6">
			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleSubmit();
				}}
				class="space-y-6"
			>
				{#if error}
					<div
						class="rounded-md bg-destructive/15 p-3 text-sm text-destructive border border-destructive/20"
					>
						{error}
					</div>
				{/if}

				<div class="grid gap-6">
					<div class="grid md:grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="date">Fecha <span class="text-destructive">*</span></Label>
							<Input id="date" type="date" bind:value={formData.date} disabled={loading} required />
						</div>
						<div class="space-y-2">
							<Label for="value">Valor <span class="text-destructive">*</span></Label>
							<Input
								id="value"
								type="number"
								step="0.000001"
								bind:value={formData.value}
								disabled={loading}
								required
								placeholder="0.000000"
							/>
							<p class="text-xs text-muted-foreground">Hasta 6 decimales de precisión.</p>
						</div>
					</div>

					<div class="grid md:grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="local_currency">Moneda Local</Label>
							<Input
								id="local_currency"
								bind:value={formData.local_currency}
								maxlength={3}
								disabled={loading}
								placeholder="MXN"
								class="uppercase"
							/>
						</div>
						<div class="space-y-2">
							<Label for="foreign_currency">Moneda Extranjera</Label>
							<Input
								id="foreign_currency"
								bind:value={formData.foreign_currency}
								maxlength={3}
								disabled={loading}
								placeholder="USD"
								class="uppercase"
							/>
						</div>
					</div>
				</div>

				<div class="flex justify-end gap-3 pt-4">
					<Button type="button" variant="outline" onclick={goBack} disabled={loading}>
						Cancelar
					</Button>
					<Button type="submit" disabled={loading || !canCreate}>
						{loading ? 'Guardando...' : 'Guardar Tipo de Cambio'}
					</Button>
				</div>
			</form>
		</Card.Content>
	</Card.Root>
</div>
{/if}
