<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 * as Dialog from '$lib/components/ui/dialog';
	import { Plus, Pencil, Trash2, Search, Image as ImageIcon, Upload } from 'lucide-svelte';
	import type { Item, Serie } from '$lib/api/dashboard/a76/items';
	import type { IdentifierDetail } from '$lib/api/dashboard/a76/general_catalogs/identifiers';
	import IdentifierCatalogSelector from './identifier-catalog-selector.svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import { m } from '$lib/i18n/messages';

	let { 
		lineItem = $bindable(),
		invoiceConsecutive = undefined,
		invoiceNumber = '',
		visibility = { showMexicanIdEnhanced: false },
		disabled = false
	}: { 
		lineItem: Partial<Item>,
		invoiceConsecutive?: number,
		invoiceNumber?: string,
		visibility?: any,
		disabled?: boolean
	} = $props();


	// Initialize identifiers if not present
	if (!lineItem.identifiers) {
		lineItem.identifiers = [];
	}
	// Initialize series if not present
	if (!lineItem.series) {
		lineItem.series = [];
	}

	let showModal = $state(false);
	let showMexModal = $state(false);
	let showCatalogSelector = $state(false);
	let isEditing = $state(false);
	let editingIndex = $state(-1);

	// State for standard Identifiers
	let currentDetail = $state<Partial<IdentifierDetail>>({
		invoice_consecutive: invoiceConsecutive || null,
		part_line: lineItem.line_number || null,
		module: 'SCAF-IT',
		identifier_code: '',
		complement1: '',
		complement2: '',
		complement3: ''
	});

	// State for MEX Assets
	let currentMexAsset = $state<Partial<Serie>>({
		number_id: '',
		import_invoice: invoiceNumber || '',
		import_line: lineItem.line_number ?? undefined,
		image_path: ''
	});

	// Standard ID Functions
	function openInsert() {
		isEditing = false;
		currentDetail = {
			invoice_consecutive: invoiceConsecutive ?? null,
			part_line: lineItem.line_number ?? null,
			module: 'SCAF-IT',
			identifier_code: '',
			complement1: '',
			complement2: '',
			complement3: ''
		};
		showModal = true;
	}

	function openEdit(index: number) {
		isEditing = true;
		editingIndex = index;
		currentDetail = { ...lineItem.identifiers![index] };
		showModal = true;
	}

	function deleteDetail(index: number) {
		lineItem.identifiers = lineItem.identifiers!.filter((_, i) => i !== index);
	}

	function saveDetail() {
		if (!lineItem.identifiers) lineItem.identifiers = [];
		if (isEditing) {
			lineItem.identifiers[editingIndex] = currentDetail as IdentifierDetail;
		} else {
			lineItem.identifiers = [...lineItem.identifiers, currentDetail as IdentifierDetail];
		}
		showModal = false;
	}

	// MEX Asset Functions
	function openMexInsert() {
		isEditing = false;
		currentMexAsset = {
			number_id: '',
			import_invoice: invoiceNumber || '',
			import_line: lineItem.line_number ?? undefined,
			image_path: ''
		};
		showMexModal = true;
	}

	function openMexEdit(index: number) {
		isEditing = true;
		editingIndex = index;
		currentMexAsset = { ...lineItem.series![index] };
		showMexModal = true;
	}

	function deleteMexAsset(index: number) {
		lineItem.series = lineItem.series!.filter((_, i) => i !== index);
	}

	function saveMexAsset() {
		if (!lineItem.series) lineItem.series = [];
		if (isEditing) {
			lineItem.series[editingIndex] = currentMexAsset as Serie;
		} else {
			lineItem.series = [...lineItem.series, currentMexAsset as Serie];
		}
		showMexModal = false;
	}

	function handleCatalogSelect(identifier: any) {
		currentDetail.identifier_code = identifier.code;
		showCatalogSelector = false;
	}

	// File selection simulation for image_path
	function triggerFileSelect() {
		// In a real scenario, this would trigger an input type="file"
		// For now we'll just simulate setting a path/name
		const simulatedPath = `assets/img_${Date.now()}.jpg`;
		currentMexAsset.image_path = simulatedPath;
	}
</script>

<div class="space-y-4">
	{#if visibility.showMexicanIdEnhanced}
		<!-- MEX Specific Layout -->
		<fieldset class="border rounded-md p-3">
			<legend class="text-xs font-semibold px-2 uppercase flex items-center gap-2">
				Activos / Num. Etiquetado (MEX)
			</legend>
			
			<div class="flex justify-end mb-2">
				<Button size="sm" variant="outline" class="h-8 text-xs gap-1" onclick={openMexInsert} disabled={disabled}>
					<Plus class="h-3 w-3" />
					Insertar Activo
				</Button>
			</div>


			<div class="border rounded-md overflow-hidden bg-white dark:bg-zinc-900">
				<Table.Root>
					<Table.Header class="bg-gray-50 dark:bg-zinc-800">
						<Table.Row class="h-8">
							<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8">{m['invoice_item_fa.identifiers.asset_number']()}</Table.Head>
							<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8">Num. Factura</Table.Head>
							<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8">Línea</Table.Head>
							<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8 text-center">Imagen</Table.Head>
							{#if !disabled}
								<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8 w-20 text-center">Acciones</Table.Head>
							{/if}
						</Table.Row>
					</Table.Header>

					<Table.Body>
						{#if lineItem.series && lineItem.series.length > 0}
							{#each lineItem.series as asset, index}
								<Table.Row class="h-8 hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors">
									<Table.Cell class="py-1 text-xs font-semibold">{asset.number_id}</Table.Cell>
									<Table.Cell class="py-1 text-xs">{asset.import_invoice || '-'}</Table.Cell>
									<Table.Cell class="py-1 text-xs">{asset.import_line || '-'}</Table.Cell>
									<Table.Cell class="py-1 text-xs text-center">
										{#if asset.image_path}
											<div class="flex justify-center">
												<ImageIcon class="h-4 w-4 text-blue-500" />
											</div>
										{:else}
											<span class="text-gray-400">-</span>
										{/if}
									</Table.Cell>
									{#if !disabled}
										<Table.Cell class="py-1 text-xs">

											<div class="flex items-center justify-center gap-1">
												<Button size="icon" variant="ghost" class="h-6 w-6 text-blue-500 hover:text-blue-600 hover:bg-blue-50" onclick={() => openMexEdit(index)}>
													<Pencil class="h-3 w-3" />
												</Button>
												<Button size="icon" variant="ghost" class="h-6 w-6 text-red-500 hover:text-red-600 hover:bg-red-50" onclick={() => deleteMexAsset(index)}>
													<Trash2 class="h-3 w-3" />
												</Button>
											</div>
										</Table.Cell>
									{/if}
								</Table.Row>

							{/each}
						{:else}
							<Table.Row>
								<Table.Cell colspan={5} class="h-20 text-center text-gray-400 text-xs italic">
									No hay activos registrados.
								</Table.Cell>
							</Table.Row>
						{/if}
					</Table.Body>
				</Table.Root>
			</div>
		</fieldset>
	{:else}
		<!-- Standard ID Layout -->
		<fieldset class="border rounded-md p-3">
			<legend class="text-xs font-semibold px-2 uppercase flex items-center gap-2">
				Tabla de Identificadores
			</legend>
			
			<div class="flex justify-end mb-2">
				<Button size="sm" variant="outline" class="h-8 text-xs gap-1" onclick={openInsert} disabled={disabled}>
					<Plus class="h-3 w-3" />
					Insertar
				</Button>
			</div>


			<div class="border rounded-md overflow-hidden bg-white dark:bg-zinc-900">
				<Table.Root>
					<Table.Header class="bg-gray-100 dark:bg-zinc-800">
						<Table.Row class="h-8">
							<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8">Clave</Table.Head>
							<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8">Compl. 1</Table.Head>
							<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8">Compl. 2</Table.Head>
							<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8">Compl. 3</Table.Head>
							{#if !disabled}
								<Table.Head class="text-[10px] uppercase font-bold text-gray-600 dark:text-gray-300 h-8 w-20 text-center">Acciones</Table.Head>
							{/if}
						</Table.Row>
					</Table.Header>

					<Table.Body>
						{#if lineItem.identifiers && lineItem.identifiers.length > 0}
							{#each lineItem.identifiers as idDetail, index}
								<Table.Row class="h-8 hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors">
									<Table.Cell class="py-1 text-xs font-semibold">{idDetail.identifier_code}</Table.Cell>
									<Table.Cell class="py-1 text-xs">{idDetail.complement1 || '-'}</Table.Cell>
									<Table.Cell class="py-1 text-xs">{idDetail.complement2 || '-'}</Table.Cell>
									<Table.Cell class="py-1 text-xs">{idDetail.complement3 || '-'}</Table.Cell>
									{#if !disabled}
										<Table.Cell class="py-1 text-xs">
											<div class="flex items-center justify-center gap-1">
												<Button size="icon" variant="ghost" class="h-6 w-6 text-blue-500 hover:text-blue-600 hover:bg-blue-50" onclick={() => openEdit(index)}>
													<Pencil class="h-3 w-3" />
												</Button>
												<Button size="icon" variant="ghost" class="h-6 w-6 text-red-500 hover:text-red-600 hover:bg-red-50" onclick={() => deleteDetail(index)}>
													<Trash2 class="h-3 w-3" />
												</Button>
											</div>
										</Table.Cell>
									{/if}
								</Table.Row>

							{/each}
						{:else}
							<Table.Row>
								<Table.Cell colspan={5} class="h-20 text-center text-gray-400 text-xs italic">
									No hay identificadores registrados.
								</Table.Cell>
							</Table.Row>
						{/if}
					</Table.Body>
				</Table.Root>
			</div>
		</fieldset>
	{/if}
</div>

<!-- Modal Standard ID -->
<Dialog.Root bind:open={showModal}>
	<Dialog.Content class="sm:max-w-[500px]">
		<Dialog.Header>
			<Dialog.Title>{isEditing ? 'Editar' : 'Insertar'} Identificador</Dialog.Title>
			<Dialog.Description>
				Ingrese los detalles del identificador para esta partida.
			</Dialog.Description>
		</Dialog.Header>

		<div class="grid grid-cols-2 gap-4 py-4">
			<div class="space-y-2">
				<Label class="text-xs">Consecutivo Factura</Label>
				<Input bind:value={currentDetail.invoice_consecutive} readonly class="h-8 text-xs bg-gray-50" />
			</div>
			<div class="space-y-2">
				<Label class="text-xs">Partida (Número)</Label>
				<Input bind:value={currentDetail.part_line} readonly class="h-8 text-xs bg-gray-50" />
			</div>
			<div class="space-y-2">
				<Label class="text-xs">Módulo</Label>
				<Input bind:value={currentDetail.module} class="h-8 text-xs" />
			</div>
			<div class="space-y-2">
				<Label class="text-xs">Clave</Label>
				<div class="flex gap-1">
					<Input bind:value={currentDetail.identifier_code} class="h-8 text-xs font-bold" placeholder="Clave" />
					<Button size="icon" variant="outline" class="h-8 w-8 shrink-0" onclick={() => showCatalogSelector = true}>
						<Search class="h-3 w-3" />
					</Button>
				</div>
			</div>
			
			<div class="col-span-2 grid grid-cols-3 gap-2">
				<div class="space-y-2">
					<Label class="text-xs">Complemento 1</Label>
					<Input bind:value={currentDetail.complement1} class="h-8 text-xs" />
				</div>
				<div class="space-y-2">
					<Label class="text-xs">Complemento 2</Label>
					<Input bind:value={currentDetail.complement2} class="h-8 text-xs" />
				</div>
				<div class="space-y-2">
					<Label class="text-xs">Complemento 3</Label>
					<Input bind:value={currentDetail.complement3} class="h-8 text-xs" />
				</div>
			</div>
		</div>

		<Dialog.Footer>
			<Button variant="outline" onclick={() => showModal = false} class="h-8 text-xs">Cancelar</Button>
			<Button onclick={saveDetail} class="h-8 text-xs">Guardar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Modal MEX Assets -->
<Dialog.Root bind:open={showMexModal}>
	<Dialog.Content class="sm:max-w-[450px]">
		<Dialog.Header>
			<Dialog.Title>{isEditing ? 'Editar' : 'Insertar'} {m['invoice_item_fa.identifiers.asset_tag_title']()}</Dialog.Title>
			<Dialog.Description>
				Detalles del etiquetado de activos para Compras Mexicanas.
			</Dialog.Description>
		</Dialog.Header>

		<div class="space-y-4 py-4">
			<!-- Info Section -->
			<div class="bg-gray-50 dark:bg-zinc-800 p-3 rounded-md grid grid-cols-2 gap-3 border">
				<div class="space-y-1">
					<Label class="text-[10px] uppercase text-gray-500">Número de Factura</Label>
					<p class="text-xs font-bold">{currentMexAsset.import_invoice || '-'}</p>
				</div>
				<div class="space-y-1">
					<Label class="text-[10px] uppercase text-gray-500">Línea de Partida</Label>
					<p class="text-xs font-bold">{currentMexAsset.import_line || '-'}</p>
				</div>
			</div>

			<!-- Input Section -->
			<div class="space-y-3">
				<div class="space-y-2">
					<Label class="text-xs">{m['invoice_item_fa.identifiers.asset_number']()}</Label>
					<Input bind:value={currentMexAsset.number_id} placeholder="Ingrese número de activo..." class="h-9 text-xs" />
				</div>
				<div class="space-y-2">
					<Label class="text-xs">Imagen del Archivo</Label>
					<div class="flex items-center gap-2">
						<div class="flex-1 h-9 px-3 py-2 border rounded-md bg-white dark:bg-zinc-900 text-xs truncate italic text-gray-500">
							{currentMexAsset.image_path || 'Ningún archivo seleccionado'}
						</div>
						<Button size="sm" variant="secondary" class="h-9 gap-1 text-xs" onclick={triggerFileSelect}>
							<Upload class="h-3 w-3" />
							Subir
						</Button>
					</div>
				</div>
			</div>
		</div>

		<Dialog.Footer>
			<Button variant="outline" onclick={() => showMexModal = false} class="h-8 text-xs">Cancelar</Button>
			<Button onclick={saveMexAsset} class="h-8 text-xs">Guardar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<IdentifierCatalogSelector 
	bind:open={showCatalogSelector} 
	onSelect={handleCatalogSelect} 
/>
