<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';
	import { FolderSearch } from 'lucide-svelte';
	import BrokerSelectorDialog from '$lib/components/dashboard/export/manifest/modals/broker-selector-dialog.svelte';
	import {
		customsBrokersApi,
		type CustomsBroker
	} from '$lib/api/dashboard/a76/customs-brokers';
	import {
		createCustomsBrokerConcept,
		updateCustomsBrokerConcept,
		type CustomsBrokerConcept,
		type CustomsBrokerConceptCreate
	} from '$lib/api/dashboard/a76/general_catalogs/customs-broker-concepts';
	import { obtenerAtajosFormularioConceptosAA } from '$lib/config/shortcuts/dashboard/general_catalogs/customs_broker_concepts/edit';

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

	// Atajos

	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? 'Editar Concepto AA' : 'Nuevo Concepto AA');

	// Estado alineado a CustomsBrokerConceptCreate
	let formData = $state<CustomsBrokerConceptCreate>({
		broker_key: '',
		concept: '',
		amount: undefined,
		priority: undefined
	});

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

	// Cargar datos al editar
	$effect(() => {
		if (item) {
			formData = {
				broker_key: item.broker_key || '',
				concept: item.concept || '',
				amount: item.amount,
				priority: item.priority
			};
			selectedBrokerLabel = item.broker_key || '';
		} else {
			formData = {
				broker_key: '',
				concept: '',
				amount: undefined,
				priority: undefined
			};
			selectedBrokerLabel = '';
		}
	});

	$effect(() => {
		if (!open || !formData.broker_key || !companyId || selectedBrokerLabel) return;

		(async () => {
			try {
				const response = await customsBrokersApi.get(formData.broker_key, companyId.toString());
				if (response.data) {
					selectedBrokerLabel = response.data.name || response.data.broker_key;
				}
			} catch (e) {
				selectedBrokerLabel = formData.broker_key;
			}
		})();
	});

	function handleBrokerSelect(broker: CustomsBroker) {
		formData.broker_key = broker.broker_key || '';
		selectedBrokerLabel = broker.name || broker.broker_key || '';
	}

	function handleBrokerClear() {
		formData.broker_key = '';
		selectedBrokerLabel = '';
	}

	const brokerDisplayValue = $derived(
		selectedBrokerLabel && selectedBrokerLabel !== formData.broker_key
			? `${selectedBrokerLabel} (${formData.broker_key})`
			: formData.broker_key
	);

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

		try {
			if (!companyId) throw new Error('No hay una compañía seleccionada');

			// Validaciones
			if (!formData.broker_key.trim()) throw new Error('La Clave del Agente es requerida');
			if (!formData.concept.trim()) throw new Error('El Concepto es requerido');

			// Limpiar y enviar datos
			const dataToSend: CustomsBrokerConceptCreate = {
				broker_key: formData.broker_key.trim(),
				concept: formData.concept.trim(),
				amount: formData.amount ? Number(formData.amount) : undefined,
				priority: formData.priority ? Number(formData.priority) : undefined
			};

			if (isEdit && item) {
				await updateCustomsBrokerConcept(item.id, dataToSend, companyId);
			} else {
				await createCustomsBrokerConcept(dataToSend, companyId);
			}

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

<Dialog.Root bind:open>
	<Dialog.Content class="max-w-lg max-h-[90vh] overflow-y-auto">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
			<Dialog.Description>
				{isEdit ? 'Modifica los detalles del concepto' : 'Ingresa los datos para el nuevo concepto'}
			</Dialog.Description>
		</Dialog.Header>

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

			<div class="grid grid-cols-2 gap-4">
				<div class="grid gap-2 col-span-1">
					<Label for="broker_key">Clave del Agente <span class="text-destructive">*</span></Label>
					<div class="flex gap-2">
						<Input
							id="broker_key"
							value={brokerDisplayValue}
							placeholder="Seleccionar agente aduanal"
							readonly
							disabled={isEdit}
							class={!isEdit ? 'cursor-pointer' : ''}
							onclick={() => {
								if (!isEdit) showBrokerSelector = true;
							}}
						/>
						<Button
							type="button"
							variant="secondary"
							size="icon"
							onclick={() => (showBrokerSelector = true)}
							disabled={isEdit}
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
				</div>

				<div class="grid gap-2 col-span-1">
					<Label for="concept">Concepto <span class="text-destructive">*</span></Label>
					<Input
						id="concept"
						bind:value={formData.concept}
						placeholder="Ej: 001"
						maxlength={15}
						disabled={isEdit}
					/>
				</div>

				<div class="grid gap-2 col-span-1">
					<Label for="amount">Importe</Label>
					<Input
						id="amount"
						type="number"
						step="0.01"
						bind:value={formData.amount}
						placeholder="0.00"
					/>
				</div>

				<div class="grid gap-2 col-span-1">
					<Label for="priority">Prioridad</Label>
					<Input id="priority" type="number" bind:value={formData.priority} placeholder="0" />
				</div>
			</div>

			<Dialog.Footer>
				<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading}>
					{loading ? 'Guardando...' : isEdit ? 'Actualizar' : 'Crear'}
				</Button>
			</Dialog.Footer>
		</form>
	</Dialog.Content>
</Dialog.Root>

<BrokerSelectorDialog bind:open={showBrokerSelector} onSelect={handleBrokerSelect} onClear={handleBrokerClear} />
