<script lang="ts">
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import * as Dialog from '$lib/components/ui/dialog';
	import * as Tabs from '$lib/components/ui/tabs';
	import { Badge } from '$lib/components/ui/badge';
	import { Button } from '$lib/components/ui/button';
	import { getInvoiceTypeColor } from '$lib/utils';

	interface Props {
		invoice: Invoice;
		onClose: () => void;
	}

	let { invoice, onClose }: Props = $props();
	let open = $state(true);

	function formatDate(dateString: string | null | undefined): string {
		if (!dateString) return '-';
		return new Date(dateString).toLocaleDateString('es-MX');
	}

	function formatCurrency(value: number | null | undefined): string {
		if (value === null || value === undefined) return '-';
		return new Intl.NumberFormat('es-MX', {
			style: 'currency',
			currency: 'MXN'
		}).format(value);
	}

	function formatNumber(value: number | null | undefined): string {
		if (value === null || value === undefined) return '-';
		return new Intl.NumberFormat('es-MX').format(value);
	}
</script>

<Dialog.Root
	{open}
	onOpenChange={(v) => {
		open = v;
		if (!v) onClose();
	}}
>
	<Dialog.Content class="max-w-5xl max-h-[90vh] overflow-y-auto">
		<Dialog.Header>
			<Dialog.Title>Detalles de Factura #{invoice?.id}</Dialog.Title>
			<Dialog.Description>Información completa de la factura</Dialog.Description>
		</Dialog.Header>

		{#if invoice}
			<Tabs.Root value="general" class="w-full">
				<Tabs.List class="grid w-full grid-cols-5">
					<Tabs.Trigger value="general">General</Tabs.Trigger>
					<Tabs.Trigger value="compliance">Cumplimiento</Tabs.Trigger>
					<Tabs.Trigger value="financials">Financieros</Tabs.Trigger>
					<Tabs.Trigger value="logistics">Logística</Tabs.Trigger>
					<Tabs.Trigger value="details">Detalles</Tabs.Trigger>
				</Tabs.List>

				<!-- General Tab -->
				<Tabs.Content value="general" class="space-y-4">
					<div class="grid grid-cols-2 gap-4">
						<div>
							<p class="text-sm font-medium text-muted-foreground">Tipo de Operación</p>
							<p class="text-base">
								{#if invoice.operation_type === 'imp'}
									<Badge>Importación</Badge>
								{:else if invoice.operation_type === 'exp'}
									<Badge variant="secondary">Exportación</Badge>
								{:else}
									-
								{/if}
							</p>
						</div>

						<div>
							<p class="text-sm font-medium text-muted-foreground">Número de Factura</p>
							<p class="text-base">{invoice.invoice_number || '-'}</p>
						</div>

						<div>
							<p class="text-sm font-medium text-muted-foreground">Tipo de Factura</p>
							<p class="text-base">
								{#if invoice.invoice_type}
									<Badge variant="outline" class={getInvoiceTypeColor(invoice.invoice_type)}
										>{invoice.invoice_type}</Badge
									>
								{:else}
									-
								{/if}
							</p>
						</div>

						<div>
							<p class="text-sm font-medium text-muted-foreground">Número de Proyecto</p>
							<p class="text-base">{invoice.project_number || '-'}</p>
						</div>

						<div>
							<p class="text-sm font-medium text-muted-foreground">Orden de Compra</p>
							<p class="text-base">{invoice.purchase_order || '-'}</p>
						</div>

						<div>
							<p class="text-sm font-medium text-muted-foreground">Fecha de Factura</p>
							<p class="text-base">{formatDate(invoice.invoice_date)}</p>
						</div>

						<div>
							<p class="text-sm font-medium text-muted-foreground">Fecha de Captura</p>
							<p class="text-base">{formatDate(invoice.capture_date)}</p>
						</div>

						<div>
							<p class="text-sm font-medium text-muted-foreground">Semáforo</p>
							<p class="text-base">{invoice.traffic_light_status || '-'}</p>
						</div>

						<div>
							<p class="text-sm font-medium text-muted-foreground">CFDI UUID</p>
							<p class="text-xs break-all">{invoice.cfdi_uuid || '-'}</p>
						</div>
						<div>
							<p class="text-sm font-medium text-muted-foreground">Actualizado</p>
							<p class="text-base">{invoice.status ? 'Sí' : 'No'}</p>
						</div>

						<div class="col-span-2">
							<p class="text-sm font-medium text-muted-foreground">Observaciones (ES)</p>
							<p class="text-base">{invoice.observation_es || '-'}</p>
						</div>

						<div class="col-span-2">
							<p class="text-sm font-medium text-muted-foreground">Observaciones (EN)</p>
							<p class="text-base">{invoice.observation_en || '-'}</p>
						</div>

						<div class="col-span-2">
							<p class="text-sm font-medium text-muted-foreground">Log de Proceso</p>
							<p class="text-base">{invoice.process_log || '-'}</p>
						</div>
					</div>
				</Tabs.Content>

				<!-- Compliance Tab -->
				<Tabs.Content value="compliance" class="space-y-4">
					{#if invoice.compliance_mx}
						<div class="grid grid-cols-2 gap-4">
							<div>
								<p class="text-sm font-medium text-muted-foreground">Pedimento</p>
								<p class="text-base font-semibold">{invoice.compliance_mx.pedimento || '-'}</p>
							</div>

							<div>
							<p class="text-sm font-medium text-muted-foreground">Código de Pedimento</p>
							<p class="text-base">{invoice.compliance_mx.pedimento?.pedimento_code || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Remesa</p>
								<p class="text-base">{invoice.compliance_mx.remesa || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Aduana</p>
								<p class="text-base">{invoice.compliance_mx.aduana || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Agente Aduanal ID</p>
								<p class="text-base">{invoice.compliance_mx.customs_broker_id || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Proveedor</p>
								<p class="text-base">{invoice.compliance_mx.provider_id || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Vendido A</p>
								<p class="text-base">{invoice.compliance_mx.sold_to_id || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Enviado A</p>
								<p class="text-base">{invoice.compliance_mx.shipped_to_id || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Enviado Por</p>
								<p class="text-base">{invoice.compliance_mx.shipped_by_id || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Operación Mixta</p>
								<p class="text-base">{invoice.compliance_mx.is_mixed ? 'Sí' : 'No'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Tipo de Desperdicio</p>
								<p class="text-base">{invoice.compliance_mx.waste_type || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Apéndice 17</p>
								<p class="text-base">{invoice.compliance_mx.appendix_17 || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">E-Document</p>
								<p class="text-base">{invoice.compliance_mx.edocument || '-'}</p>
							</div>

							<div class="col-span-2">
								<p class="text-sm font-medium text-muted-foreground">Firma Electrónica</p>
								<p class="text-xs break-all">{invoice.compliance_mx.electronic_signature || '-'}</p>
							</div>
						</div>
					{:else}
						<p class="text-muted-foreground">No hay información de cumplimiento disponible.</p>
					{/if}
				</Tabs.Content>

				<!-- Financials Tab -->
				<Tabs.Content value="financials" class="space-y-4">
					{#if invoice.financials}
						<div class="grid grid-cols-2 gap-4">
							<div>
								<p class="text-sm font-medium text-muted-foreground">Moneda</p>
								<p class="text-base">{invoice.financials.currency || '-'}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Tipo de Cambio</p>
								<p class="text-base">{formatNumber(invoice.financials.exchange_rate)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Valor MN</p>
								<p class="text-base font-semibold">{formatCurrency(invoice.financials.value_mn)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Valor ME</p>
								<p class="text-base font-semibold">{formatNumber(invoice.financials.value_me)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Valor Aduana MN</p>
								<p class="text-base">{formatCurrency(invoice.financials.customs_value_mn)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Flete</p>
								<p class="text-base">{formatCurrency(invoice.financials.freight)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Seguro</p>
								<p class="text-base">{formatCurrency(invoice.financials.insurance)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">IVA MN</p>
								<p class="text-base">{formatCurrency(invoice.financials.iva_mn)}</p>
							</div>

							<div>
							<p class="text-sm font-medium text-muted-foreground">Factor IVA</p>
							<p class="text-base">{formatCurrency(invoice.financials.iva_factor)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Cantidad Total</p>
								<p class="text-base">{formatNumber(invoice.financials.total_quantity)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Peso Bruto</p>
								<p class="text-base">{formatNumber(invoice.financials.gross_weight)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Peso Neto</p>
								<p class="text-base">{formatNumber(invoice.financials.net_weight)}</p>
							</div>

							<div>
								<p class="text-sm font-medium text-muted-foreground">Número de Bultos</p>
								<p class="text-base">{invoice.financials.bundle_count || '-'}</p>
							</div>
						</div>
					{:else}
						<p class="text-muted-foreground">No hay información financiera disponible.</p>
					{/if}
				</Tabs.Content>

				<!-- Logistics Tab -->
				<Tabs.Content value="logistics" class="space-y-4">
					{#if invoice.logistics}
						<div class="space-y-6">							
							<div class="border rounded-lg p-4">
								<h4 class="font-semibold mb-3">Logística</h4>
								<div class="grid grid-cols-2 gap-4">
									<div>
										<p class="text-sm font-medium text-muted-foreground">Transportista</p>
										<p class="text-base">{invoice.logistics.carrier_id || '-'}</p>
									</div>

									<div>
										<p class="text-sm font-medium text-muted-foreground">Tipo de Transporte</p>
										<p class="text-base">{invoice.logistics.transport_type || '-'}</p>
									</div>

									<div>
										<p class="text-sm font-medium text-muted-foreground">Modo de Transporte</p>
										<p class="text-base">{invoice.logistics.transport_mode || '-'}</p>
									</div>

									<div>
										<p class="text-sm font-medium text-muted-foreground">Conductor</p>
										<p class="text-base">{invoice.logistics.driver_name || '-'}</p>
									</div>

									<div>
										<p class="text-sm font-medium text-muted-foreground">Número de Vehículo</p>
										<p class="text-base">{invoice.logistics.vehicle_num || '-'}</p>
									</div>

									<div>
										<p class="text-sm font-medium text-muted-foreground">Placa</p>
										<p class="text-base">{invoice.logistics.license_plate || '-'}</p>
									</div>

									<div>
										<p class="text-sm font-medium text-muted-foreground">Número de Sello</p>
										<p class="text-base">{invoice.logistics.seal_number || '-'}</p>
									</div>

									<div>
										<p class="text-sm font-medium text-muted-foreground">Guía</p>
										<p class="text-base">{invoice.logistics.guide_number || '-'}</p>
									</div>

									<div>
										<p class="text-sm font-medium text-muted-foreground">Fecha Entrada/Salida</p>
										<p class="text-base">{formatDate(invoice.logistics.entry_exit_date)}</p>
									</div>
								</div>
							</div>							
						</div>
					{:else}
						<p class="text-muted-foreground">No hay información de logística disponible.</p>
					{/if}
				</Tabs.Content>

				<!-- Details Tab -->
				<Tabs.Content value="details" class="space-y-4">
					{#if invoice.details && invoice.details.length > 0}
						<div class="space-y-6">
							<div>
								<h4 class="font-semibold mb-3">Detalles de Venta</h4>
								<div class="space-y-3">
									{#each invoice.details as detail}
										<div class="border rounded-lg p-4">
											<div class="grid grid-cols-2 gap-4">
												<div>
													<p class="text-sm font-medium text-muted-foreground">Línea</p>
													<p class="text-base">{detail.line_number}</p>
												</div>

												<div>
													<p class="text-sm font-medium text-muted-foreground">Orden de Venta</p>
													<p class="text-base">{detail.sales_order || '-'}</p>
												</div>

												<div>
													<p class="text-sm font-medium text-muted-foreground">
														Descripción de Colores
													</p>
													<p class="text-base">{detail.colors_description || '-'}</p>
												</div>

												<div>
													<p class="text-sm font-medium text-muted-foreground">Código de Color</p>
													<p class="text-base">{detail.square_color_code || '-'}</p>
												</div>

												<div>
													<p class="text-sm font-medium text-muted-foreground">Bultos</p>
													<p class="text-base">{detail.line_bundles || '-'}</p>
												</div>
											</div>
										</div>
									{/each}
								</div>
							</div>

							{#if invoice.collections && invoice.collections.length > 0}
								<div>
									<h4 class="font-semibold mb-3">Cobranzas</h4>
									<div class="space-y-3">
										{#each invoice.collections as collection}
											<div class="border rounded-lg p-4">
												<div class="grid grid-cols-2 gap-4">
													<div>
														<p class="text-sm font-medium text-muted-foreground">Concepto</p>
														<p class="text-base">{collection.concept || '-'}</p>
													</div>

													<div>
														<p class="text-sm font-medium text-muted-foreground">Monto</p>
														<p class="text-base">{formatCurrency(collection.amount)}</p>
													</div>

													<div>
														<p class="text-sm font-medium text-muted-foreground">
															Fecha de Cobranza
														</p>
														<p class="text-base">{formatDate(collection.collection_date)}</p>
													</div>

													<div>
														<p class="text-sm font-medium text-muted-foreground">Cobrado</p>
														<p class="text-base">{collection.is_collected ? 'Sí' : 'No'}</p>
													</div>

													<div>
														<p class="text-sm font-medium text-muted-foreground">Cobrador</p>
														<p class="text-base">{collection.collector_user || '-'}</p>
													</div>
												</div>
											</div>
										{/each}
									</div>
								</div>
							{/if}
						</div>
					{:else}
						<p class="text-muted-foreground">No hay detalles de venta o cobranzas disponibles.</p>
					{/if}
				</Tabs.Content>
			</Tabs.Root>
		{/if}

		<Dialog.Footer>
			<Button variant="outline" onclick={() => (open = false)}>Cerrar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
