<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, Trash2, CheckCircle2, AlertTriangle, AlertCircle } from 'lucide-svelte';
	import { itemsApi, type Item, type LineDescriptions, type Serie } from '$lib/api/dashboard/a76/items';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import { companyStore } from '$lib/stores/company.svelte';
	import { toast } from 'svelte-sonner';

	let seriesErrorMessage = $state('');

	let {
		descriptions = $bindable(),
		series = $bindable(),
		lineItem,
		invoice,
		disabled = false
	}: {
		descriptions: LineDescriptions;
		series: Serie[] | Serie;
		lineItem: Partial<Item>;
		invoice: Invoice | null;
		disabled?: boolean;
	} = $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;
	}

	function deleteSerie(index: number) {
		const arr = ensureSeriesArray();
		const newArr = arr.filter((_, i) => i !== index);
		// Update row numbers for remaining series
		newArr.forEach((s, i) => (s.row = i + 1));
		series = newArr;
		if (selectedSeriesIndex === index) {
			selectedSeriesIndex = null;
		} else if (selectedSeriesIndex !== null && selectedSeriesIndex > index) {
			selectedSeriesIndex--;
		}
	}

	async function clearAllSeries() {
		if (seriesList.length === 0) return;
		
		const confirmed = confirm(`¿Estás seguro de que deseas borrar TODAS las series de esta partida? Esta acción no se puede deshacer.`);
		if (!confirmed) return;

		try {
			// Si la partida ya existe en la DB, llamamos al endpoint de borrado físico
			if (lineItem.id && companyStore.activeCompany?.id) {
				await itemsApi.deleteSeries(lineItem.id, companyStore.activeCompany.id);
				toast.success('Series eliminadas correctamente y registrado en bitácora.');
			}
			
			// Limpiar el estado local
			series = [];
			selectedSeriesIndex = null;
		} catch (err) {
			console.error('Error clearing series:', err);
			seriesErrorMessage = 'No se pudieron borrar las series. Intenta de nuevo.';
		}
	}

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

	const internalHasSerial = $derived(descriptions?.has_serial === true);
	
	const hasSerial = $derived(internalHasSerial);

	// 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 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" 
				checked={descriptions?.has_serial === true} 
				disabled={disabled}
				onCheckedChange={(v: boolean) => { if (descriptions) descriptions.has_serial = v; }} 
			/>
			<Label for="has_serial" class="text-xs font-normal">Lleva serie (LLEVASERIE)</Label>

		</div>
		<div class="flex items-center gap-2">
			<Button
				type="button"
				variant="outline"
				size="sm"
				class="h-7 text-xs text-red-600 hover:text-red-700 hover:bg-red-50 border-red-200"
				onclick={clearAllSeries}
				disabled={disabled || !hasSerial || seriesList.length === 0}
			>

				<AlertTriangle class="w-3.5 h-3.5 mr-1" />
				Limpiar todas
			</Button>

			<Button
				type="button"
				variant="outline"
				size="sm"
				class="h-7 text-xs"
				onclick={addNewSerie}
				disabled={disabled || !canAddNewSerie}
			>

				<Plus class="w-3.5 h-3.5 mr-1" />
				Nueva serie
			</Button>
		</div>
	</div>

	<!-- Table of all series for this item -->
	<div class="rounded-md border overflow-hidden max-h-[300px] overflow-y-auto">
		<Table.Root>
			<Table.Header class="sticky top-0 bg-white dark:bg-zinc-950 z-10">
				<Table.Row class="bg-muted/50">
					<Table.Head class="w-12 text-center text-[10px] uppercase">Línea</Table.Head>
					<Table.Head class="text-[10px] uppercase text-center">Serie</Table.Head>
					<Table.Head class="text-[10px] uppercase text-center">Modelo</Table.Head>
					<Table.Head class="text-[10px] uppercase text-center">Sub modelo</Table.Head>
					<Table.Head class="text-[10px] uppercase text-center">Núm. ID</Table.Head>
					<Table.Head class="w-[80px] text-right text-[10px] uppercase">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 || disabled ? 'opacity-70' : ''}"
							onclick={() => hasSerial && !disabled && 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 text-center" title={serie.serial_numbers}>
								{serie.serial_numbers || '-'}
							</Table.Cell>
							<Table.Cell class="text-xs max-w-[100px] truncate text-center" title={serie.model}>
								{serie.model || '-'}
							</Table.Cell>
							<Table.Cell class="text-xs max-w-[100px] truncate text-center" title={serie.sub_model}>
								{serie.sub_model || '-'}
							</Table.Cell>
							<Table.Cell class="text-xs text-center">{serie.number_id || '-'}</Table.Cell>
							<Table.Cell class="text-right flex items-center justify-end gap-1">
								<Button
									type="button"
									variant="ghost"
									size="icon"
									class="h-7 w-7 text-blue-600"
									disabled={disabled || !hasSerial}
									onclick={(e) => {
										e.stopPropagation();
										if (hasSerial && !disabled) selectForEdit(i);
									}}
								>

									<Pencil class="w-3.5 h-3.5" />
								</Button>
								<Button
									type="button"
									variant="ghost"
									size="icon"
									class="h-7 w-7 text-red-600 hover:text-red-700 hover:bg-red-50"
									disabled={disabled || !hasSerial}
									onclick={(e) => {
										e.stopPropagation();
										if (hasSerial && !disabled) deleteSerie(i);
									}}
								>

									<Trash2 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-2 border-primary/20 space-y-3 bg-primary/5 p-3 rounded-lg animate-in fade-in slide-in-from-top-2 duration-300">
			<div class="flex items-center justify-between">
				<div class="flex items-center gap-2">
					<div class="w-2 h-2 bg-primary rounded-full"></div>
					<span class="text-xs font-bold uppercase tracking-wider text-primary">
						{selectedSeriesIndex >= (seriesList.length - 1) && !currentSerie?.id
							? 'Capturando Nueva serie'
							: `Editando serie (línea ${currentSerie.row ?? selectedSeriesIndex + 1})`}
					</span>
				</div>
				<div class="flex gap-2">
					<Button 
						type="button" 
						variant="default" 
						size="sm" 
						class="h-7 text-xs bg-emerald-600 hover:bg-emerald-700 text-white gap-1" 
						onclick={clearSelection}
					>
						{#if !disabled}
							<CheckCircle2 class="w-3.5 h-3.5" />
							Aceptar / Listo
						{:else}
							Cerrar
						{/if}
					</Button>
					{#if !disabled}
						<Button type="button" variant="outline" size="sm" class="h-7 text-xs" onclick={clearSelection}>
							Cancelar
						</Button>
					{/if}

				</div>
			</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 font-semibold">NUMERO FACTURA:</Label>
					<div
						id="invoice_number"
						class="flex h-8 w-full items-center rounded-md border border-input bg-muted/60 px-3 text-sm text-foreground font-mono"
					>
						{invoiceNumber || '-'}
					</div>
				</div>
				<div class="space-y-2">
					<Label for="invoice_line" class="text-xs font-semibold">LINEA FACTURA:</Label>
					<div
						id="invoice_line"
						class="flex h-8 w-full items-center rounded-md border border-input bg-muted/60 px-3 text-sm text-foreground font-mono"
					>
						{invoiceLine || '-'}
					</div>
				</div>
				<div class="space-y-2">
					<Label for="series_row" class="text-xs font-semibold">LINEA SERIE:</Label>
					<Input
						id="series_row"
						bind:value={currentSerie.row}
						class="h-8 text-sm focus:ring-primary"
						type="number"
						min={1}
						step={1}
						disabled={disabled || !hasSerial}
						onblur={clampRowToInteger}
					/>

				</div>
				<div class="space-y-2">
					<Label for="serial_number" class="text-xs font-semibold">SERIE:</Label>
					<Input
						id="serial_number"
						value={currentSerie.serial_numbers ?? ''}
						class="h-8 text-sm focus:ring-primary"
						maxlength={50}
						placeholder="Número de serie..."
						disabled={disabled || !hasSerial}
						oninput={(e) => handleSerieInput(e, 'serial_numbers')}
					/>

				</div>
				<div class="space-y-2">
					<Label for="series_model" class="text-xs font-semibold">MODELO:</Label>
					<Input
						id="series_model"
						value={currentSerie.model ?? ''}
						class="h-8 text-sm focus:ring-primary"
						maxlength={50}
						placeholder="Modelo..."
						disabled={disabled || !hasSerial}
						oninput={(e) => handleSerieInput(e, 'model')}
					/>

				</div>
				<div class="space-y-2">
					<Label for="part_number" class="text-xs font-semibold">NUM PARTE:</Label>
					<div
						id="part_number"
						class="flex h-8 w-full items-center rounded-md border border-input bg-muted/60 px-3 text-sm text-foreground font-mono"
					>
						{partNumber || '-'}
					</div>
				</div>
				<div class="space-y-2">
					<Label for="sub_model" class="text-xs font-semibold">SUB MODELO:</Label>
					<Input
						id="sub_model"
						value={currentSerie.sub_model ?? ''}
						class="h-8 text-sm focus:ring-primary"
						maxlength={50}
						placeholder="Sub modelo..."
						disabled={disabled || !hasSerial}
						oninput={(e) => handleSerieInput(e, 'sub_model')}
					/>

				</div>
				<div class="space-y-2">
					<Label for="number_id" class="text-xs font-semibold">NUMERO ID:</Label>
					<Input
						id="number_id"
						value={currentSerie.number_id ?? ''}
						class="h-8 text-sm focus:ring-primary"
						maxlength={25}
						placeholder="Número ID..."
						disabled={disabled || !hasSerial}
						oninput={(e) => handleSerieInput(e, 'number_id')}
					/>

				</div>
			</div>
			{#if !disabled}
				<div class="flex justify-end pt-1">
					<Button 
						type="button" 
						variant="ghost" 
						size="sm" 
						class="h-7 text-xs text-red-600 hover:text-red-700 hover:bg-red-50 gap-1" 
						onclick={() => deleteSerie(selectedSeriesIndex!)}
					>
						<Trash2 class="w-3.5 h-3.5" />
						Eliminar esta serie
					</Button>
				</div>
			{/if}

		</div>
	{/if}

	<div class="text-xs text-muted-foreground italic bg-zinc-50 dark:bg-zinc-900 p-2 rounded border-l-4 border-zinc-300">
		{#if !hasSerial}
			Los datos capturados se conservan, pero la edición queda deshabilitada mientras "Lleva serie" esté apagado.
		{:else}
			Se permiten hasta {maxSeriesAllowed === Infinity ? 'ilimitadas' : maxSeriesAllowed} series para esta partida.
		{/if}
	</div>
</fieldset>

<style>
	/* Animación para el formulario de edición */
	.animate-in {
		animation: fadeInSlide 0.3s ease-out;
	}
	@keyframes fadeInSlide {
		from {
			opacity: 0;
			transform: translateY(-8px);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>
