<script lang="ts">
	import * as Table from '$lib/components/ui/table';
	import { Input } from '$lib/components/ui/input';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { Label } from '$lib/components/ui/label';
	import { Button } from '$lib/components/ui/button';
	import { Plus, Pencil } from 'lucide-svelte';
	import type { Item, LineDescriptions, Serie } from '$lib/api/dashboard/a76/items';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';

	let {
		descriptions = $bindable(),
		series = $bindable(),
		lineItem,
		invoice
	}: {
		descriptions: LineDescriptions;
		series: Serie[] | Serie;
		lineItem: Partial<Item>;
		invoice: Invoice | null;
	} = $props();

	// Normalize to array for display and mutations
	const seriesList = $derived(
		Array.isArray(series) ? series : series != null ? [series] : []
	);

	let selectedSeriesIndex = $state<number | null>(null);

	// Ensure series is array in parent when we mutate (for bindable)
	function ensureSeriesArray(): Serie[] {
		const arr = Array.isArray(series) ? series : series != null ? [series] : [];
		if (!Array.isArray(series)) {
			series = arr;
		}
		return arr;
	}

	function addNewSerie() {
		const arr = ensureSeriesArray();
		const newSerie: Serie = {
			row: arr.length + 1,
			serial_numbers: '',
			model: '',
			sub_model: '',
			number_id: ''
		};
		series = [...arr, newSerie];
		selectedSeriesIndex = (series as Serie[]).length - 1;
	}

	function selectForEdit(index: number) {
		selectedSeriesIndex = index;
	}

	function clearSelection() {
		selectedSeriesIndex = null;
	}

	// Current serie being edited (reference into the array)
	const currentSerie = $derived(
		selectedSeriesIndex !== null && seriesList[selectedSeriesIndex] != null
			? seriesList[selectedSeriesIndex]
			: null
	);

	// Ensure descriptions.has_serial has default
	$effect(() => {
		if (descriptions && descriptions.has_serial === undefined) {
			descriptions.has_serial = false;
		}
	});

	// Ensure current serie has defaults for form fields
	$effect(() => {
		const s = currentSerie;
		if (s) {
			if (s.serial_numbers === undefined) s.serial_numbers = '';
			if (s.model === undefined) s.model = '';
			if (s.sub_model === undefined) s.sub_model = '';
			if (s.number_id === undefined) s.number_id = '';
			if (s.row === undefined) s.row = 1;
		}
	});

	const hasSerial = $derived(Boolean(descriptions?.has_serial));
	const invoiceNumber = $derived(invoice?.invoice_number || '');
	const invoiceLine = $derived(lineItem?.line_number != null ? String(lineItem.line_number) : '');
	const partNumber = $derived((lineItem as any)?.part_number_display || lineItem?.part_number || '');

	// Restricción cantidad: no más series que la cantidad de la partida (paridad CSV DEF/EXPO)
	const maxSeriesAllowed = $derived(
		lineItem?.quantity?.quantity != null && Number(lineItem.quantity.quantity) >= 0
			? Number(lineItem.quantity.quantity)
			: Infinity
	);
	const canAddNewSerie = $derived(hasSerial && seriesList.length < maxSeriesAllowed);

	// Normalizar texto: comas y saltos de línea → espacio, colapsar espacios (SACARCOMASENTERS)
	function normalizeSerieText(val: string): string {
		if (val == null) return '';
		return String(val)
			.replace(/,/g, ' ')
			.replace(/\r\n/g, ' ')
			.replace(/\n/g, ' ')
			.replace(/\r/g, ' ')
			.replace(/\s+/g, ' ')
			.trim();
	}

	function handleSerieInput(
		e: Event & { currentTarget: HTMLInputElement },
		field: 'serial_numbers' | 'model' | 'sub_model' | 'number_id'
	) {
		const s = currentSerie;
		if (!s) return;
		const raw = e.currentTarget.value;
		const normalized = normalizeSerieText(raw);
		(s as any)[field] = normalized;
		if (normalized !== raw) {
			e.currentTarget.value = normalized;
			e.currentTarget.setSelectionRange(normalized.length, normalized.length);
		}
	}

	function clampRowToInteger() {
		const s = currentSerie;
		if (!s) return;
		const n = Number(s.row);
		const clamped = Math.max(1, Math.floor(Number.isFinite(n) ? n : 1));
		s.row = clamped;
	}
</script>

<fieldset class="border rounded-md p-3 space-y-3">
	<legend class="text-xs font-semibold px-2 uppercase">Series</legend>

	<div class="flex items-center justify-between gap-2 flex-wrap">
		<div class="flex items-center space-x-1.5">
			<Checkbox id="has_serial" bind:checked={descriptions.has_serial} />
			<Label for="has_serial" class="text-xs font-normal">Lleva serie (LLEVASERIE)</Label>
		</div>
		<Button
			type="button"
			variant="outline"
			size="sm"
			class="h-7 text-xs"
			onclick={addNewSerie}
			disabled={!canAddNewSerie}
		>
			<Plus class="w-3.5 h-3.5 mr-1" />
			Nueva serie
		</Button>
	</div>

	<!-- Table of all series for this item -->
	<div class="rounded-md border overflow-hidden">
		<Table.Root>
			<Table.Header>
				<Table.Row class="bg-muted/50">
					<Table.Head class="w-12 text-center text-xs">Línea</Table.Head>
					<Table.Head class="text-xs">Serie</Table.Head>
					<Table.Head class="text-xs">Modelo</Table.Head>
					<Table.Head class="text-xs">Sub modelo</Table.Head>
					<Table.Head class="text-xs">Núm. ID</Table.Head>
					<Table.Head class="w-[80px] text-right text-xs">Acciones</Table.Head>
				</Table.Row>
			</Table.Header>
			<Table.Body>
				{#if seriesList.length === 0}
					<Table.Row>
						<Table.Cell colspan={6} class="py-4 text-center text-muted-foreground text-xs">
							No hay series registradas. Usa "Nueva serie" para agregar una.
						</Table.Cell>
					</Table.Row>
				{:else}
					{#each seriesList as serie, i (i)}
						<Table.Row
							class="cursor-pointer hover:bg-muted/50 {selectedSeriesIndex === i
								? 'bg-primary/10 dark:bg-primary/20'
								: ''} {!hasSerial ? 'opacity-70' : ''}"
							onclick={() => hasSerial && selectForEdit(i)}
						>
							<Table.Cell class="text-center text-xs font-medium">{serie.row ?? i + 1}</Table.Cell>
							<Table.Cell class="text-xs max-w-[120px] truncate" title={serie.serial_numbers}>
								{serie.serial_numbers || '-'}
							</Table.Cell>
							<Table.Cell class="text-xs max-w-[100px] truncate" title={serie.model}>
								{serie.model || '-'}
							</Table.Cell>
							<Table.Cell class="text-xs max-w-[100px] truncate" title={serie.sub_model}>
								{serie.sub_model || '-'}
							</Table.Cell>
							<Table.Cell class="text-xs">{serie.number_id || '-'}</Table.Cell>
							<Table.Cell class="text-right">
								<Button
									type="button"
									variant="ghost"
									size="icon"
									class="h-7 w-7"
									disabled={!hasSerial}
									onclick={(e) => {
										e.stopPropagation();
										if (hasSerial) selectForEdit(i);
									}}
								>
									<Pencil class="w-3.5 h-3.5" />
								</Button>
							</Table.Cell>
						</Table.Row>
					{/each}
				{/if}
			</Table.Body>
		</Table.Root>
	</div>

	<!-- Form for selected or new serie -->
	{#if currentSerie && selectedSeriesIndex !== null}
		<div class="mt-3 pt-3 border-t space-y-3">
			<div class="flex items-center justify-between">
				<span class="text-xs font-medium text-muted-foreground">
					{selectedSeriesIndex >= seriesList.length - 1 && !currentSerie?.id
						? 'Nueva serie'
						: `Editar serie (línea ${currentSerie.row ?? selectedSeriesIndex + 1})`}
				</span>
				<Button type="button" variant="ghost" size="sm" class="h-6 text-xs" onclick={clearSelection}>
					Cerrar formulario
				</Button>
			</div>
			<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
				<div class="space-y-2">
					<Label for="invoice_number" class="text-xs">NUMERO FACTURA:</Label>
					<div
						id="invoice_number"
						class="flex h-8 w-full items-center rounded-md border border-input bg-muted/40 px-3 text-sm text-foreground"
					>
						{invoiceNumber || '-'}
					</div>
				</div>
				<div class="space-y-2">
					<Label for="invoice_line" class="text-xs">LINEA FACTURA:</Label>
					<div
						id="invoice_line"
						class="flex h-8 w-full items-center rounded-md border border-input bg-muted/40 px-3 text-sm text-foreground"
					>
						{invoiceLine || '-'}
					</div>
				</div>
				<div class="space-y-2">
					<Label for="series_row" class="text-xs">LINEA SERIE:</Label>
					<Input
						id="series_row"
						bind:value={currentSerie.row}
						class="h-8 text-sm"
						type="number"
						min={1}
						step={1}
						disabled={!hasSerial}
						onblur={clampRowToInteger}
					/>
				</div>
				<div class="space-y-2">
					<Label for="serial_number" class="text-xs">SERIE:</Label>
					<Input
						id="serial_number"
						value={currentSerie.serial_numbers ?? ''}
						class="h-8 text-sm"
						maxlength={50}
						placeholder="Número de serie..."
						disabled={!hasSerial}
						oninput={(e) => handleSerieInput(e, 'serial_numbers')}
					/>
				</div>
				<div class="space-y-2">
					<Label for="series_model" class="text-xs">MODELO:</Label>
					<Input
						id="series_model"
						value={currentSerie.model ?? ''}
						class="h-8 text-sm"
						maxlength={50}
						placeholder="Modelo..."
						disabled={!hasSerial}
						oninput={(e) => handleSerieInput(e, 'model')}
					/>
				</div>
				<div class="space-y-2">
					<Label for="part_number" class="text-xs">NUM PARTE:</Label>
					<div
						id="part_number"
						class="flex h-8 w-full items-center rounded-md border border-input bg-muted/40 px-3 text-sm text-foreground"
					>
						{partNumber || '-'}
					</div>
				</div>
				<div class="space-y-2">
					<Label for="sub_model" class="text-xs">SUB MODELO:</Label>
					<Input
						id="sub_model"
						value={currentSerie.sub_model ?? ''}
						class="h-8 text-sm"
						maxlength={50}
						placeholder="Sub modelo..."
						disabled={!hasSerial}
						oninput={(e) => handleSerieInput(e, 'sub_model')}
					/>
				</div>
				<div class="space-y-2">
					<Label for="number_id" class="text-xs">NUMERO ID:</Label>
					<Input
						id="number_id"
						value={currentSerie.number_id ?? ''}
						class="h-8 text-sm"
						maxlength={25}
						placeholder="Número ID..."
						disabled={!hasSerial}
						oninput={(e) => handleSerieInput(e, 'number_id')}
					/>
				</div>
			</div>
		</div>
	{/if}

	<div class="text-xs text-muted-foreground">
		{#if !hasSerial}
			Los datos capturados se conservan, pero la edición queda deshabilitada mientras "Lleva serie" esté apagado.
		{/if}
	</div>
</fieldset>
