<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Button } from '$lib/components/ui/button';
	import { Textarea } from '$lib/components/ui/textarea';
	import {
		createTariffFraction,
		updateTariffFraction,
		type TariffFraction,
		type TariffFractionCreate,
		type TariffFractionUpdate
	} from '$lib/api/dashboard/a76/general_catalogs/tariff-fractions';
	import { companyStore } from '$lib/stores/company.svelte';
	import { toast } from 'svelte-sonner';
	import { Loader2 } from 'lucide-svelte';
	import { currentUser } from '$lib/auth';
	import {
		canCreateTariffFractionCatalog,
		canEditTariffFractionCatalog,
		resolveTariffFractionBasePrefix
	} from '$lib/permissions/tariff-fraction-permissions';

	let {
		open = $bindable(false),
		fraction = null, // If null, create mode. If set, edit mode.
		catalog = 'mex',
		catalogBasePrefix = null,
		onSuccess
	}: {
		open: boolean;
		fraction?: TariffFraction | null;
		catalog?: string;
		/** Prefijo RBAC explícito (p. ej. frac_sitar_7); si null se deduce del catalog */
		catalogBasePrefix?: string | null;
		onSuccess: () => void;
	} = $props();

	const basePrefix = $derived(resolveTariffFractionBasePrefix(catalog, catalogBasePrefix));

	let isLoading = $state(false);

	// Form fields
	let code = $state('');
	let fractionFormatted = $state('');
	let description = $state('');
	let nico = $state('');
	let umt = $state('');
	let adv_impo = $state('');
	let adv_expo = $state('');
	let um_code = $state(''); // New field for unit code

	// Load data on open/fraction change
	$effect(() => {
		if (open) {
			if (fraction) {
				// Edit mode
				code = fraction.code;
				fractionFormatted = fraction.fraction;
				description = fraction.description || '';
				nico = fraction.nico || '';
				umt = fraction.umt || '';
				adv_impo = fraction.adv_impo || '';
				adv_expo = fraction.adv_expo || '';
				um_code = fraction.um_code || '';
			} else {
				// Create mode - reset
				code = '';
				fractionFormatted = '';
				description = '';
				nico = '';
				umt = '';
				adv_impo = '';
				adv_expo = '';
				um_code = '';
			}
		}
	});

	// Sync code with fractionFormatted for US catalog
	$effect(() => {
		if (catalog === 'usa' || catalog === 'american') {
			code = fractionFormatted.replace(/\./g, '').replace(/-/g, '');
		}
	});

	async function handleSubmit() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		if (fraction) {
			if (!canEditTariffFractionCatalog($currentUser, basePrefix)) {
				toast.error('No tienes permiso para editar fracciones en este catálogo');
				return;
			}
		} else {
			if (!canCreateTariffFractionCatalog($currentUser, basePrefix)) {
				toast.error('No tienes permiso para crear fracciones en este catálogo');
				return;
			}
		}

		isLoading = true;
		try {
			if (fraction) {
				// Update
				const updateData: TariffFractionUpdate = {
					fraction: fractionFormatted,
					description,
					nico: catalog === 'mex' ? nico : null,
					umt,
					adv_impo,
					adv_expo
				};
				await updateTariffFraction(fraction.id, updateData, companyId, catalog);
				toast.success('Fracción actualizada correctamente');
			} else {
				// Create
				const createData: TariffFractionCreate = {
					code,
					fraction: fractionFormatted,
					description,
					nico: catalog === 'mex' ? nico : null,
					umt,
					adv_impo,
					adv_expo
				};
				await createTariffFraction(createData, companyId, catalog);
				toast.success('Fracción creada correctamente');
			}
			onSuccess();
		} catch (error) {
			console.error('Error saving fraction:', error);
			toast.error('Error al guardar la fracción');
		} finally {
			isLoading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[600px]">
		<Dialog.Header>
			<Dialog.Title
				>{fraction ? 'Editar' : 'Crear'} Fracción Arancelaria {catalog === 'usa'
					? '(USA)'
					: ''}</Dialog.Title
			>
			<Dialog.Description>
				{fraction
					? 'Modifica los detalles de la fracción seleccionada.'
					: 'Ingresa los datos para la nueva fracción.'}
			</Dialog.Description>
		</Dialog.Header>

		<div class="grid gap-4 py-4">
			<div class="grid grid-cols-2 gap-4">
				<div class="space-y-2">
					<Label for="code">{catalog === 'mex' ? 'Clave / Código (Sin puntos)' : 'Clave'}</Label>
					<Input id="code" bind:value={code} disabled={true} placeholder="Ej. 01012101" />
					<p class="text-[10px] text-muted-foreground">
						{catalog === 'mex'
							? 'El código se genera automáticamente.'
							: 'La clave se deriva de la fracción sin puntos.'}
					</p>
				</div>
				<div class="space-y-2">
					<Label for="fraction"
						>{catalog === 'mex' ? 'Fracción (Con puntos)' : 'Fracción (HTS Code)'}</Label
					>
					<Input
						id="fraction"
						bind:value={fractionFormatted}
						placeholder={catalog === 'mex' ? 'Ej. 0101.21.01' : 'Ej. 1234.56.78'}
					/>
				</div>
			</div>

			<div class="space-y-2">
				<Label for="description">Descripción</Label>
				<Textarea
					id="description"
					bind:value={description}
					placeholder="Descripción de la mercancía..."
				/>
			</div>

			{#if catalog === 'mex'}
				<div class="grid grid-cols-3 gap-4">
					<div class="space-y-2">
						<Label for="nico">NICO</Label>
						<Input id="nico" bind:value={nico} placeholder="Ej. 00" />
					</div>
					<div class="space-y-2">
						<Label for="um_code">Clave U.M.</Label>
						<Input id="um_code" bind:value={um_code} placeholder="Ej. 06" />
					</div>
					<div class="space-y-2">
						<Label for="umt">U.M.T</Label>
						<Input id="umt" bind:value={umt} placeholder="Ej. Kg" />
					</div>
				</div>
			{:else}
				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="umt">Unidad de Medida</Label>
						<Input id="umt" bind:value={umt} placeholder="Unit" />
					</div>
				</div>
			{/if}

			<div class="grid grid-cols-2 gap-4">
				<div class="space-y-2">
					<Label for="adv_impo">Adv. Impo</Label>
					<Input id="adv_impo" bind:value={adv_impo} placeholder="Ej. Ex." />
				</div>
				<div class="space-y-2">
					<Label for="adv_expo">Adv. Expo</Label>
					<Input id="adv_expo" bind:value={adv_expo} placeholder="Ej. Ex." />
				</div>
			</div>
		</div>

		<Dialog.Footer>
			<Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
			<Button onclick={handleSubmit} disabled={isLoading}>
				{#if isLoading}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
				{/if}
				Guardar
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
