<script lang="ts">
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Button } from '$lib/components/ui/button';
	import * as Table from '$lib/components/ui/table';
	import { Plus, Pencil, Trash2, Folder } from 'lucide-svelte';
	import type { Item, LineDescriptions, Serie } from '$lib/api/dashboard/a76/items';
	import ValuationMethodSelector from './valuation-method-selector.svelte';
	import { m } from '$lib/i18n/messages';

	let { 
		lineItem = $bindable(),
		descriptions = $bindable(),
		visibility,
		disabled = false
	}: { 
		lineItem: Partial<Item>,
		descriptions: LineDescriptions,
		visibility: any,
		disabled?: boolean
	} = $props();


	// Ensure series is an array
	if (!lineItem.series) {
		lineItem.series = [];
	}

	let valuationSelectorOpen = $state(false);
	
	// Asset management state
	let selectedAssetIndex = $state<number | null>(null);
	let editingAsset = $state<Serie>({
		row: 0,
		number_id: '',
		import_invoice: '',
		import_line: undefined
	});

	function handleValuationMethodSelect(method: { key: string }) {
		lineItem.valuation_method = method.key;
	}

	function addAsset() {
		const newAsset: Serie = {
			row: (lineItem.series?.length || 0) + 1,
			number_id: '',
			import_invoice: '',
			import_line: undefined
		};
		lineItem.series = [...(lineItem.series || []), newAsset];
		editAsset((lineItem.series || []).length - 1);
	}

	function editAsset(index: number) {
		selectedAssetIndex = index;
		editingAsset = { ...(lineItem.series?.[index] as Serie) };
	}

	function saveAsset() {
		if (selectedAssetIndex !== null && lineItem.series) {
			const updatedSeries = [...lineItem.series];
			updatedSeries[selectedAssetIndex] = { ...editingAsset };
			lineItem.series = updatedSeries;
			selectedAssetIndex = null;
		}
	}

	function deleteAsset(index: number) {
		if (lineItem.series) {
			lineItem.series = lineItem.series.filter((_, i) => i !== index);
			// Re-index rows
			lineItem.series = lineItem.series.map((s, i) => ({ ...s, row: i + 1 }));
			if (selectedAssetIndex === index) {
				selectedAssetIndex = null;
			} else if (selectedAssetIndex !== null && selectedAssetIndex > index) {
				selectedAssetIndex--;
			}
		}
	}

	function cancelAssetEdit() {
		selectedAssetIndex = null;
	}
</script>

<div class="grid grid-cols-1 {visibility.showLabelingLeftSection ? 'md:grid-cols-2' : ''} gap-2">
	{#if visibility.showLabelingLeftSection}
		<!-- Left Side: Labeling & Valuation -->
		<fieldset class="border rounded-md p-2 space-y-2">
			<legend class="text-xs font-semibold px-2 bg-gray-200 dark:bg-gray-700 uppercase">{m['invoice_item_fa.labeling.legend']()}</legend>
			
			{#if visibility.showLabelingStandard}
				<div class="grid grid-cols-2 gap-2">
					<div class="space-y-1">
						<Label for="numero_etiqueta" class="text-xs">{m['invoice_item_fa.labeling.label_number']()}:</Label>
						<Input id="numero_etiqueta" bind:value={descriptions.lot} disabled={disabled} class="h-7 text-xs" />
					</div>
					<div class="space-y-1">
						<Label for="tipo_etiqueta" class="text-xs">{m['invoice_item_fa.labeling.label_type']()}:</Label>
						<Input id="tipo_etiqueta" bind:value={descriptions.entry_number} disabled={disabled} class="h-7 text-xs" />
					</div>

				</div>
			{/if}

			<div class="grid grid-cols-2 gap-2">
				{#if visibility.showLabelingEnhanced}
					{#if visibility.showLabelingQuantity}
						<div class="space-y-1">
							<Label for="cantidad_importar" class="text-xs">Cantidad a importar:</Label>
							<Input 
								id="cantidad_importar" 
								type="number" 
								bind:value={lineItem.quantity!.quantity} 
								disabled={disabled}
								class="h-7 text-xs" 
							/>
						</div>

					{/if}
					{#if visibility.showLabelingValuationValue}
						<div class="space-y-1">
							<Label for="valor_det" class="text-xs">Valor Det:</Label>
							<Input 
								id="valor_det" 
								type="number" 
								step="0.00000001"
								bind:value={lineItem.valuation_determined_value} 
								disabled={disabled}
								class="h-7 text-xs" 
							/>
						</div>

					{/if}
				{/if}
			</div>

			{#if visibility.showLabelingEnhanced}
				{#if visibility.showLabelingValuationMethod}
					<div class="space-y-1">
						<Label for="metodos_valoracion" class="text-xs">Métodos de valoración:</Label>
						<div class="flex gap-1">
							<Input 
								id="metodos_valoracion" 
								bind:value={lineItem.valuation_method} 
								disabled={disabled}
								class="h-7 text-xs flex-1" 
								placeholder="Seleccione..."
							/>
							<Button 
								size="icon" 
								variant="outline" 
								class="h-7 w-7"
								disabled={disabled}
								onclick={() => (valuationSelectorOpen = true)}
							>
								<Folder class="h-3 w-3" />
							</Button>
						</div>
					</div>

				{/if}

				{#if visibility.showUsageReason}
					<div class="space-y-1">
						<Label for="motivo_uso" class="text-xs">Motivo de uso:</Label>
						<Input 
							id="motivo_uso" 
							bind:value={lineItem.valuation_reason} 
							disabled={disabled}
							class="h-7 text-xs" 
							placeholder="Especifique motivo..."
						/>
					</div>

				{/if}
			{/if}


			{#if visibility.showLabelingObservations}
				<div class="space-y-1">
					<Label for="observaciones_etiqueta" class="text-xs">{m['invoice_item_fa.labeling.observations']()}:</Label>
					<textarea 
						id="observaciones_etiqueta"
						bind:value={descriptions.additional_info_spanish}
						disabled={disabled}
						class="flex min-h-[60px] w-full rounded-md border border-input bg-background px-3 py-1.5 text-xs ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
						placeholder={m['invoice_item_fa.labeling.observations_placeholder']()}
					></textarea>
				</div>

			{/if}
		</fieldset>
	{/if}

	{#if visibility.showLabelingEnhanced}
		<!-- Right Side: Assets Table -->
		<fieldset class="border rounded-md p-2 space-y-2">
			<legend class="text-xs font-semibold px-2 bg-gray-200 dark:bg-gray-700 uppercase">{m['invoice_item_fa.labeling.assets_series']()}</legend>
			
			<div class="flex justify-end">
				<Button size="sm" variant="outline" class="h-7 text-xs px-2" onclick={addAsset} disabled={disabled}>
					<Plus class="h-3 h-3 mr-1" /> Insertar Activo
				</Button>
			</div>


			<div class="rounded-md border overflow-hidden max-h-[180px] overflow-y-auto">
				<Table.Root>
					<Table.Header>
						<Table.Row class="bg-muted/50 h-7">
							<Table.Head class="w-8 text-center text-[10px] p-0 px-1">#</Table.Head>
							<Table.Head class="text-[10px] p-0 px-1">{m['invoice_item_fa.labeling.asset_number_short']()}</Table.Head>
							<Table.Head class="text-[10px] p-0 px-1">Factura</Table.Head>
							<Table.Head class="text-[10px] p-0 px-1">Línea</Table.Head>
							{#if !disabled}
								<Table.Head class="w-14 text-right text-[10px] p-0 px-2">{m['invoice_item_fa.labeling.actions_short']()}</Table.Head>
							{/if}
						</Table.Row>
					</Table.Header>

					<Table.Body>
						{#each lineItem.series || [] as asset, i}
							<Table.Row class="hover:bg-muted/50 h-7">
								<Table.Cell class="text-center text-[10px] p-0 px-1 font-medium">{asset.row || i+1}</Table.Cell>
								<Table.Cell class="text-[10px] p-0 px-1 truncate max-w-[60px]">{asset.number_id || '-'}</Table.Cell>
								<Table.Cell class="text-[10px] p-0 px-1 truncate max-w-[60px]">{asset.import_invoice || '-'}</Table.Cell>
								<Table.Cell class="text-[10px] p-0 px-1">{asset.import_line || '-'}</Table.Cell>
								{#if !disabled}
									<Table.Cell class="text-right p-0 px-2">
										<div class="flex justify-end gap-0.5">
											<Button variant="ghost" size="icon" class="h-5 w-5" onclick={() => editAsset(i)}>
												<Pencil class="h-2.5 w-2.5" />
											</Button>
											<Button variant="ghost" size="icon" class="h-5 w-5 text-destructive" onclick={() => deleteAsset(i)}>
												<Trash2 class="h-2.5 w-2.5" />
											</Button>
										</div>
									</Table.Cell>
								{/if}
							</Table.Row>

						{:else}
							<Table.Row>
								<Table.Cell colspan={5} class="h-12 text-center text-muted-foreground text-[10px]">
									No hay activos.
								</Table.Cell>
							</Table.Row>
						{/each}
					</Table.Body>
				</Table.Root>
			</div>

			{#if selectedAssetIndex !== null}
				<div class="p-2 border rounded bg-muted/20 space-y-2">
					<div class="text-[10px] font-semibold uppercase">Editar #{editingAsset.row}</div>
					<div class="grid grid-cols-2 gap-2">
						<div class="space-y-0.5">
							<Label class="text-[10px]">{m['invoice_item_fa.labeling.asset_number']()}</Label>
							<Input bind:value={editingAsset.number_id} class="h-6 text-[10px]" />
						</div>
						<div class="space-y-0.5">
							<Label class="text-[10px]">Factura Impo</Label>
							<Input bind:value={editingAsset.import_invoice} class="h-6 text-[10px]" />
						</div>
						<div class="space-y-0.5">
							<Label class="text-[10px]">Linea Impo</Label>
							<Input type="number" bind:value={editingAsset.import_line} class="h-6 text-[10px]" />
						</div>
					</div>
					<div class="flex justify-end gap-1.5 pt-1">
						<Button size="sm" variant="ghost" class="h-6 text-[10px] px-2" onclick={cancelAssetEdit}>{m['invoice_item_fa.labeling.cancel']()}</Button>
						<Button size="sm" class="h-6 text-[10px] px-2" onclick={saveAsset}>{m['invoice_item_fa.labeling.save']()}</Button>
					</div>
				</div>
			{/if}
		</fieldset>
	{/if}
</div>

<ValuationMethodSelector 
	bind:open={valuationSelectorOpen} 
	onSelect={handleValuationMethodSelect} 
/>
