<script lang="ts">
	import { onMount } from 'svelte';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import {
		Plus,
		Pencil,
		Trash2,
		Loader2,
		Save,
		ArrowLeft,
		Package,
		FileText,
		Search,
		Sparkles
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { goto } from '$app/navigation';
	import { itemPresetsApi, type ItemPreset } from '$lib/api/dashboard/a76/item-presets';
	import { itemsApi, type Item } from '$lib/api/dashboard/a76/items';
	import { companyStore } from '$lib/stores/company.svelte';
	import * as Table from '$lib/components/ui/table';
	import * as Dialog from '$lib/components/ui/dialog';
	import ItemSheetFa from '$lib/components/dashboard/invoices/edit/items/fa/item-sheet-fa.svelte';
	import ItemSheetInv from '$lib/components/dashboard/invoices/edit/items/inv/item-sheet-inv.svelte';

	let presets = $state<ItemPreset[]>([]);
	let searchTerm = $state('');
	let isLoading = $state(true);
	let isSaving = $state(false);
	let showEditor = $state(false);
	let isEditMode = $state(false);
	let selectedPreset = $state<Partial<ItemPreset>>({
		name: '',
		description: '',
		items: []
	});

	// Item Editor State (mimicking ItemsTabForm)
	let showItemSheet = $state(false);
	let isItemEditMode = $state(false);
	let editingItemIndex = $state<number | null>(null);
	let editingItem = $state<Partial<Item>>({});
	let itemSystem = $state<'fixed_asset' | 'scaii'>('scaii');

	const activeCompanyId = $derived(companyStore.activeCompany?.id);

	const filteredPresets = $derived(
		presets.filter((preset) => {
			const term = searchTerm.trim().toLowerCase();
			if (!term) return true;
			return (
				preset.name.toLowerCase().includes(term) ||
				preset.description?.toLowerCase().includes(term)
			);
		})
	);

	const totalPresetItems = $derived(
		presets.reduce((acc, preset) => acc + (preset.items?.length || 0), 0)
	);

	$effect(() => {
		if (activeCompanyId) {
			loadPresets();
		}
	});

	async function loadPresets() {
		if (!activeCompanyId) return;
		isLoading = true;
		try {
			const response = await itemPresetsApi.list(activeCompanyId);
			presets = response.data || [];
		} catch (error) {
			console.error('Error loading presets:', error);
			toast.error('Error al cargar presets');
		} finally {
			isLoading = false;
		}
	}

	function handleAdd() {
		isEditMode = false;
		selectedPreset = {
			name: '',
			description: '',
			items: []
		};
		showEditor = true;
	}

	function handleEditPreset(preset: ItemPreset) {
		isEditMode = true;
		selectedPreset = JSON.parse(JSON.stringify(preset));
		// Basic inference of system from first item
		if (selectedPreset.items && selectedPreset.items.length > 0) {
			// This is a bit arbitrary, but scaii is default
			itemSystem = 'scaii';
		}
		showEditor = true;
	}

	async function handleDeletePreset(id: number) {
		if (!activeCompanyId || !confirm('¿Estás seguro de eliminar esta plantilla?')) return;
		try {
			await itemPresetsApi.delete(id, activeCompanyId);
			toast.success('Plantilla eliminada');
			loadPresets();
		} catch (error) {
			console.error('Error deleting preset:', error);
			toast.error('Error al eliminar plantilla');
		}
	}

	async function handleSavePreset() {
		if (!activeCompanyId || !selectedPreset.name) {
			toast.warning('El nombre es obligatorio');
			return;
		}

		isSaving = true;
		try {
			if (isEditMode && selectedPreset.id) {
				await itemPresetsApi.update(selectedPreset.id, activeCompanyId, {
					name: selectedPreset.name,
					description: selectedPreset.description,
					items: selectedPreset.items
				});
				toast.success('Plantilla actualizada');
			} else {
				await itemPresetsApi.create(activeCompanyId, {
					name: selectedPreset.name!,
					description: selectedPreset.description,
					items: selectedPreset.items || []
				});
				toast.success('Plantilla creada');
			}
			showEditor = false;
			loadPresets();
		} catch (error) {
			console.error('Error saving preset:', error);
			toast.error('Error al guardar plantilla');
		} finally {
			isSaving = false;
		}
	}

	// --- Item Management Logic (within Preset) ---

	function handleAddItem() {
		isItemEditMode = false;
		editingItemIndex = null;
		editingItem = {						
			line_number: (selectedPreset.items?.length || 0) + 1,
			quantity: { quantity: 1 },
			financial: { unit_cost_usd: 0 },
			customs: {},
			description: {},
			reference: {}		
		};
		showItemSheet = true;
	}

	function handleEditItem(index: number) {
		isItemEditMode = true;
		editingItemIndex = index;
		editingItem = JSON.parse(JSON.stringify(selectedPreset.items![index]));
		showItemSheet = true;
	}

	function handleDeleteItem(index: number) {
		selectedPreset.items!.splice(index, 1);
		selectedPreset.items = [...selectedPreset.items!]; // Trigger reactivity
	}

	function saveItemToPreset() {
		if (isItemEditMode && editingItemIndex !== null) {
			selectedPreset.items![editingItemIndex] = editingItem as any;
		} else {
			selectedPreset.items = [...(selectedPreset.items || []), editingItem as any];
		}
		showItemSheet = false;
		toast.success(
			isItemEditMode ? 'Partida actualizada en plantilla' : 'Partida añadida a plantilla'
		);
	}

	// Mock invoice to satisfy ItemSheets
	const mockInvoice = $derived({
		system: itemSystem,
		invoice_number: 'PLANTILLA',
		operation_type: 'exp',
		purchase_order: ''
	} as any);
</script>

<div class="container mx-auto py-6">
	<div class="mb-6 flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
		<div class="flex items-center gap-4">
			<Button variant="ghost" size="icon" onclick={() => goto('/dashboard/invoices')}>
				<ArrowLeft class="h-5 w-5" />
			</Button>
			<div>
				<h1 class="text-2xl font-bold tracking-tight">Plantillas de Partidas</h1>
				<p class="text-muted-foreground text-sm">
					Gestiona, edita y prueba plantillas reutilizables sin perderte en la UI.
				</p>
			</div>
		</div>
		<div class="flex gap-2 flex-wrap">
			<Button variant="outline" size="sm" onclick={loadPresets} disabled={isLoading}>
				<Loader2 class={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
				Refrescar
			</Button>
			<Button onclick={handleAdd}>
				<Plus class="mr-2 h-4 w-4" />
				Nueva Plantilla
			</Button>
		</div>
	</div>

	<div class="grid gap-3 md:grid-cols-3 mb-6">
		<div class="bg-white dark:bg-zinc-950 border rounded-lg p-4 shadow-sm">
			<p class="text-xs uppercase text-muted-foreground font-semibold">Total plantillas</p>
			<p class="text-2xl font-bold mt-1">{presets.length}</p>
		</div>
		<div class="bg-white dark:bg-zinc-950 border rounded-lg p-4 shadow-sm">
			<p class="text-xs uppercase text-muted-foreground font-semibold">Partidas totales</p>
			<p class="text-2xl font-bold mt-1">{totalPresetItems}</p>
		</div>
		<div class="bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-lg p-4 shadow-sm flex items-center justify-between">
			<div>
				<p class="text-xs uppercase font-semibold opacity-80">Tip</p>
				<p class="text-sm mt-1 opacity-90">Usa plantillas para acelerar la captura.</p>
			</div>
			<Sparkles class="h-6 w-6 opacity-80" />
		</div>
	</div>

	<Card.Root>
		<Card.Header class="pb-3">
			<div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
				<div class="space-y-1">
					<Card.Title class="text-base">Listado de plantillas</Card.Title>
					<Card.Description>Mira, filtra y edita tus plantillas guardadas.</Card.Description>
				</div>
				<div class="relative w-full lg:w-64">
					<Search class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
					<Input
						placeholder="Buscar por nombre o descripción"
						class="pl-9"
						bind:value={searchTerm}
					/>
				</div>
			</div>
		</Card.Header>
		<Card.Content class="p-0">
			<Table.Root>
				<Table.Header>
					<Table.Row>
						<Table.Head>Nombre</Table.Head>
						<Table.Head>Descripción</Table.Head>
						<Table.Head class="text-center">Items</Table.Head>
						<Table.Head>Fecha</Table.Head>
						<Table.Head class="text-right">Acciones</Table.Head>
					</Table.Row>
				</Table.Header>
				<Table.Body>
					{#if isLoading}
						<Table.Row>
							<Table.Cell colspan={5} class="text-center py-10">
								<Loader2 class="h-8 w-8 animate-spin mx-auto text-primary" />
							</Table.Cell>
						</Table.Row>
					{:else}
						{#each filteredPresets as preset}
							<Table.Row class="hover:bg-muted/40 transition-colors">
								<Table.Cell class="font-medium">{preset.name}</Table.Cell>
								<Table.Cell class="max-w-[280px] text-sm text-muted-foreground">
									<span class="line-clamp-2">{preset.description || 'Sin descripción'}</span>
								</Table.Cell>
								<Table.Cell class="text-center text-sm font-semibold">
									{preset.items?.length || 0} partidas
								</Table.Cell>
								<Table.Cell class="text-sm text-muted-foreground">
									{preset.created_at
										? new Date(preset.created_at).toLocaleDateString()
										: '-'}
								</Table.Cell>
								<Table.Cell class="text-right">
									<div class="flex justify-end gap-2">
										<Button size="icon" variant="ghost" onclick={() => handleEditPreset(preset)}>
											<Pencil class="h-4 w-4" />
										</Button>
										<Button
											size="icon"
											variant="ghost"
											onclick={() => handleDeletePreset(preset.id)}
										>
											<Trash2 class="h-4 w-4 text-destructive" />
										</Button>
									</div>
								</Table.Cell>
							</Table.Row>
						{/each}
						{#if filteredPresets.length === 0}
							<Table.Row>
								<Table.Cell colspan={5} class="text-center py-12 text-muted-foreground">
									<div class="flex flex-col items-center gap-2">
										<Package class="h-8 w-8 opacity-30" />
										<p class="text-sm">No hay plantillas que coincidan con tu búsqueda.</p>
										<Button variant="outline" size="sm" onclick={handleAdd}>
											<Plus class="w-4 h-4 mr-2" /> Crear la primera
										</Button>
									</div>
								</Table.Cell>
							</Table.Row>
						{/if}
					{/if}
				</Table.Body>
			</Table.Root>
		</Card.Content>
	</Card.Root>
</div>

<!-- Editor como popup modal -->
<Dialog.Root bind:open={showEditor}>
	<Dialog.Content class="sm:max-w-5xl max-h-[90vh] p-0 overflow-hidden">
		<div class="bg-white dark:bg-zinc-950 border-b dark:border-zinc-800 px-6 py-4 shadow-sm flex items-start justify-between gap-3">
			<div class="flex items-center gap-3">
				<div class="bg-primary/10 p-2 rounded-lg text-primary">
					<Package class="h-5 w-5" />
				</div>
				<div class="space-y-1">
					<Dialog.Title class="text-lg font-bold">
						{isEditMode ? 'Editar Plantilla' : 'Nueva Plantilla'}
					</Dialog.Title>
					<Dialog.Description class="text-sm text-muted-foreground">
						Configura los items que compondrán esta plantilla.
					</Dialog.Description>
				</div>
			</div>
			<div class="flex gap-2">
				<Button variant="outline" onclick={() => (showEditor = false)} disabled={isSaving}
					>Cancelar</Button
				>
				<Button
					onclick={handleSavePreset}
					disabled={isSaving}
					class="bg-blue-600 hover:bg-blue-700 text-white"
				>
					{#if isSaving}
						<Loader2 class="mr-2 h-4 w-4 animate-spin" />
						Guardando...
					{:else}
						<Save class="mr-2 h-4 w-4" />
						{isEditMode ? 'Actualizar Plantilla' : 'Crear Plantilla'}
					{/if}
				</Button>
			</div>
		</div>

		<div class="p-6 overflow-auto max-h-[calc(90vh-88px)] bg-slate-50/70 dark:bg-black">
			<div class="max-w-6xl mx-auto space-y-6">
				<!-- Metadata Card -->
				<div class="bg-white dark:bg-zinc-950 p-6 rounded-lg border shadow-sm space-y-4">
					<h3 class="text-xs font-semibold uppercase tracking-wider text-zinc-500">
						Información General
					</h3>
					<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
						<div class="space-y-2">
							<Label for="name">Nombre de la Plantilla</Label>
							<Input
								id="name"
								bind:value={selectedPreset.name}
								placeholder="Ej. Aceros Estándar"
								class="bg-slate-50/50"
							/>
						</div>
						<div class="space-y-2">
							<Label for="description">Descripción (Opcional)</Label>
							<Input
								id="description"
								bind:value={selectedPreset.description}
								placeholder="Breve descripción..."
								class="bg-slate-50/50"
							/>
						</div>
					</div>
				</div>

				<!-- Items Management Card -->
				<div class="bg-white dark:bg-zinc-950 p-6 rounded-lg border shadow-sm space-y-4">
					<div class="flex justify-between items-start gap-3 flex-wrap">
						<div class="flex flex-col">
							<h3 class="text-xs font-semibold uppercase tracking-wider text-zinc-500">
								Partidas de la Plantilla
							</h3>
							<p class="text-[11px] text-muted-foreground mt-1">
								Estas partidas se inyectarán en la factura al cargar la plantilla.
							</p>
						</div>
						<div class="flex items-center gap-3">
							<div class="flex items-center gap-2 mr-2">
								<Label class="text-[11px] text-zinc-400">Sistema:</Label>
								<select
									bind:value={itemSystem}
									class="text-[11px] border rounded-md px-2 py-1 bg-slate-50 dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800"
								>
									<option value="scaii">SCAII (Inventario)</option>
									<option value="fixed_asset">Fixed Asset</option>
								</select>
							</div>
							<Button size="sm" onclick={handleAddItem} class="h-8">
								<Plus class="w-3.5 h-3.5 mr-2" />
								Agregar Partida
							</Button>
						</div>
					</div>

					<div class="border rounded-md overflow-hidden bg-white dark:bg-zinc-950">
						<Table.Root>
							<Table.Header class="bg-zinc-50 dark:bg-zinc-900/50">
								<Table.Row>
									<Table.Head class="w-12 text-center">#</Table.Head>
									<Table.Head>Descripción (ES)</Table.Head>
									<Table.Head class="text-center">Cantidad</Table.Head>
									<Table.Head class="text-center">Precio (USD)</Table.Head>
									<Table.Head class="text-right pr-6">Acciones</Table.Head>
								</Table.Row>
							</Table.Header>
							<Table.Body>
								{#if !selectedPreset.items || selectedPreset.items.length === 0}
									<Table.Row>
										<Table.Cell colspan={5} class="text-center py-16 text-muted-foreground">
											<div class="flex flex-col items-center gap-2">
												<Package class="h-8 w-8 opacity-20" />
												<p class="text-sm italic">No hay partidas agregadas aún.</p>
												<Button
													variant="ghost"
													size="sm"
													onclick={handleAddItem}
													class="mt-2 text-primary"
												>
													Haz clic aquí para agregar la primera
												</Button>
											</div>
										</Table.Cell>
									</Table.Row>
								{:else}
									{#each selectedPreset.items as item, i}
										<Table.Row class="hover:bg-slate-50/50 dark:hover:bg-zinc-900/30">
											<Table.Cell class="text-center font-mono text-[11px] text-zinc-400"
												>{i + 1}</Table.Cell
											>
											<Table.Cell>
												<div class="flex flex-col">
													<span class="font-medium text-sm">
														{item?.description?.description_spanish || 'Sin descripción'}
													</span>
													{#if item.reference_number}
														<span class="text-[10px] text-muted-foreground flex items-center gap-1">
															<FileText class="w-3 h-3" /> Ref: {item.reference_number}
														</span>
													{/if}
												</div>
											</Table.Cell>
											<Table.Cell class="text-center tabular-nums font-medium"
												>{item?.quantity?.quantity || 0}</Table.Cell
											>
											<Table.Cell
												class="text-center tabular-nums font-medium text-emerald-600 dark:text-emerald-400"
											>
												${(item?.financial?.unit_cost_usd || 0).toLocaleString()}
											</Table.Cell>
											<Table.Cell class="text-right pr-6">
												<div class="flex justify-end gap-1">
													<Button
														size="icon"
														variant="ghost"
														onclick={() => handleEditItem(i)}
														class="h-8 w-8 text-zinc-500 hover:text-primary"
													>
														<Pencil class="h-3.5 w-3.5" />
													</Button>
													<Button
														size="icon"
														variant="ghost"
														onclick={() => handleDeleteItem(i)}
														class="h-8 w-8 text-zinc-500 hover:text-destructive"
													>
														<Trash2 class="h-3.5 w-3.5" />
													</Button>
												</div>
											</Table.Cell>
										</Table.Row>
									{/each}
								{/if}
							</Table.Body>
						</Table.Root>
					</div>

					{#if selectedPreset.items && selectedPreset.items.length > 0}
						<div class="flex justify-between items-center text-[11px] text-muted-foreground px-1">
							<p>
								Total de partidas: <span class="font-bold text-zinc-900 dark:text-zinc-100"
									>{selectedPreset.items.length}</span
								>
							</p>
						</div>
					{/if}
				</div>
			</div>
		</div>
	</Dialog.Content>
</Dialog.Root>

<!-- Reuse ItemSheets -->
{#if itemSystem === 'fixed_asset'}
	<ItemSheetFa
		bind:open={showItemSheet}
		isEditMode={isItemEditMode}
		bind:editingItem
		invoice={mockInvoice}
		onSave={saveItemToPreset}
		onCancel={() => (showItemSheet = false)}
		isSaving={false}
	/>
{:else}
	<ItemSheetInv
		bind:open={showItemSheet}
		isEditMode={isItemEditMode}
		bind:editingItem
		invoice={mockInvoice}
		onSave={saveItemToPreset}
		onCancel={() => (showItemSheet = false)}
		isSaving={false}
	/>
{/if}
