<script lang="ts">
	import { onMount } from 'svelte';
	import { customsBrokersApi, type CustomsBroker } from '$lib/api/dashboard/a76/customs-brokers';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Plus, RefreshCw, Building2, MapPin, Mail, Phone, FileText, Hash } from 'lucide-svelte';
	import * as Tabs from '$lib/components/ui/tabs';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';
	import { browser } from '$app/environment';
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaAgentes } from '$lib/config/shortcuts/dashboard/customs_brokers/list';

	import {
		customsSectionsApi,
		type CustomsSection
	} from '$lib/api/dashboard/reference_data/customs_sections';
	import SectionsDataTable from '$lib/components/dashboard/reference_data/customs_sections/data-table.svelte';
	import { createColumns as createSectionColumns } from '$lib/components/dashboard/reference_data/customs_sections/columns.js';
	import * as Card from '$lib/components/ui/card';

	// Specialized Broker Components
	import BrokerDataTable from '$lib/components/dashboard/customs_brokers/data-table.svelte';
	import { createColumns as createBrokerColumns } from '$lib/components/dashboard/customs_brokers/columns';
	import DeleteDialog from '$lib/components/dashboard/customs_brokers/delete-dialog.svelte';

	let { data }: { data: any } = $props();

	// Global State
	let activeTab = $state('brokers');

	// --- Brokers State ---
	let items = $state<CustomsBroker[]>(data.items || []);
	let selectedItem = $state<CustomsBroker | null>(null);
	let isLoading = $state(false);
	let showDeleteDialog = $state(false);

	// Server-side filtering/pagination (for Brokers)
	let allItemsRaw = $state<CustomsBroker[]>(data.brokers || []);
	let searchName = $state('');
	let searchPatent = $state('');
	let currentPage = $state(1);
	let pageSize = $state(50);

	let filteredItems = $derived(
		allItemsRaw.filter((item) => {
			const matchesName =
				!searchName || (item.name?.toLowerCase().includes(searchName.toLowerCase()) ?? false);
			const matchesPatent =
				!searchPatent ||
				(item.broker_key?.toLowerCase().includes(searchPatent.toLowerCase()) ?? false);
			return matchesName && matchesPatent;
		})
	);

	let paginatedItems = $derived(
		filteredItems.slice((currentPage - 1) * pageSize, currentPage * pageSize)
	);
	let totalItems = $derived(filteredItems.length);

	// --- Customs Sections State ---
	let sections = $state<CustomsSection[]>([]);
	let loadingSections = $state(false);
	let totalSections = $state(0);
	let sectionsPage = $state(1);
	let hasMoreSections = $derived(sections.length < totalSections);

	// --- Lifecycle ---
	onMount(() => {
		if (browser) {
			const handleCompanyChange = () => {
				loadItems();
				loadSections();
			};
			window.addEventListener('companyChanged', handleCompanyChange);
			// Initial load for sections if not loaded
			loadSections();
			return () => window.removeEventListener('companyChanged', handleCompanyChange);
		}
	});

	// --- Actions ---

	// Brokers Actions
	async function loadItems() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;
		isLoading = true;
		try {
			const response = await customsBrokersApi.list(companyId.toString());
			if ((response as any).error) {
				toast.error((response as any).error);
				return;
			}
			const d = (response as any).data || response;
			if (Array.isArray(d)) {
				allItemsRaw = d;
			} else if ((d as any).items) {
				allItemsRaw = (d as any).items;
			}
			currentPage = 1;
		} catch (e: any) {
			console.error('Error loading items:', e);
			toast.error('Error al cargar datos');
		} finally {
			isLoading = false;
		}
	}
	function handleSearch() {
		currentPage = 1;
	}
	function selectItem(item: CustomsBroker) {
		selectedItem = item;
	}
	function handleEdit() {
		if (selectedItem) goto(`/dashboard/customs_brokers/edit/${selectedItem.broker_key}`);
	}
	async function handleDelete() {
		if (!selectedItem || !companyStore.activeCompany?.id) return;
		showDeleteDialog = true;
	}

	function handleActionSuccess() {
		loadItems();
		selectedItem = null;
		toast.success('Cambios aplicados correctamente');
	}

	// Customs Sections Actions
	async function loadSections() {
		// Simple loading logic reusing existing API
		// Assuming we load all or paginate - trying to match existing page logic
		if (loadingSections) return;
		loadingSections = true;
		try {
			const response = await customsSectionsApi.list(sectionsPage, 50);
			if (response.data?.items) {
				sections = sectionsPage === 1 ? response.data.items : [...sections, ...response.data.items];
				totalSections = response.data.total;
			}
		} catch (e) {
			console.error('Error loading sections', e);
		} finally {
			loadingSections = false;
		}
	}

	async function loadMoreSections() {
		if (loadingSections || !hasMoreSections) return;
		sectionsPage++;
		await loadSections();
	}

	// Shortcuts Integration
	useShortcuts(
		'Customs Brokers List',
		obtenerAtajosListaAgentes({
			irAgentes: () => (activeTab = 'brokers'),
			irAduanas: () => (activeTab = 'customs'),
			crear: () => {
				if (activeTab === 'brokers') {
					goto('/dashboard/customs_brokers/edit/new');
				} else {
					// For Customs Sections, we might need a dialog.
					// Since we are "not modifying logic", we'll just show a toast or Placeholder TODO
					toast.info('Crear Sección Aduanal: Implementación pendiente de diálogo');
				}
			},
			recargar: () => {
				if (activeTab === 'brokers') loadItems();
				else {
					sectionsPage = 1;
					loadSections();
				}
			}
		})
	);

	const sectionsColumns = createSectionColumns(() => {
		sectionsPage = 1;
		loadSections();
	});

	const brokerColumns = createBrokerColumns(handleActionSuccess);
</script>

<div class="flex flex-col h-[calc(100vh-4rem)] p-4 gap-4 pb-15">
	<!-- Title -->
	<div class="flex items-center justify-between">
		<div class="flex flex-col gap-1">
			<h1 class="text-2xl font-bold">GESTIÓN ADUANAL</h1>
			<p class="text-sm text-muted-foreground">Administración de Agentes y Secciones Aduanales</p>
		</div>
	</div>

	<Tabs.Root bind:value={activeTab} class="flex-1 flex flex-col overflow-hidden">
		<Tabs.List class="w-full justify-start border-b rounded-none bg-transparent p-0 mb-4">
			<Tabs.Trigger
				value="brokers"
				class="data-[state=active]:border-primary border-b-2 border-transparent rounded-none"
			>
				Agentes Aduanales
			</Tabs.Trigger>
			<Tabs.Trigger
				value="customs"
				class="data-[state=active]:border-primary border-b-2 border-transparent rounded-none"
			>
				Secciones Aduanales
			</Tabs.Trigger>
		</Tabs.List>

		<Tabs.Content
			value="brokers"
			class="flex-1 flex gap-4 overflow-hidden mt-0 data-[state=inactive]:hidden"
		>
			<!-- Left Panel: Table -->
			<div class="flex-1 flex flex-col gap-4 overflow-hidden">
				<!-- Filters -->
				<div class="border rounded-lg bg-card">
					<div class="p-4 space-y-4">
						<div class="flex items-center justify-between">
							<h2 class="text-sm font-semibold">Filtros</h2>
							<span class="text-xs text-muted-foreground">Busque por nombre o patente</span>
						</div>
						<div class="grid grid-cols-3 gap-4">
							<div class="space-y-2">
								<Label class="text-xs">Nombre</Label>
								<Input
									bind:value={searchName}
									placeholder="Buscar por nombre..."
									class="h-9"
									oninput={handleSearch}
								/>
							</div>
							<div class="space-y-2">
								<Label class="text-xs">Patente / Clave</Label>
								<Input
									bind:value={searchPatent}
									placeholder="Num. Patente..."
									class="h-9"
									oninput={handleSearch}
								/>
							</div>
							<div class="flex items-end">
								<!-- Placeholder for layout balance -->
							</div>
						</div>
					</div>
				</div>

				<!-- Table -->
				<div class="flex-1 flex flex-col border rounded-lg overflow-hidden">
					<div class="flex items-center justify-between p-3 border-b bg-muted/30">
						<h2 class="text-sm font-semibold">Listado</h2>
						<div class="flex items-center gap-2">
							<span class="text-xs text-muted-foreground">
								{filteredItems.length} registros
							</span>
							<Button variant="outline" size="sm" onclick={loadItems}>
								<RefreshCw class="h-4 w-4 mr-2" />
								Actualizar
							</Button>
						</div>
					</div>

					<div class="flex-1 overflow-auto bg-card">
						<BrokerDataTable
							data={paginatedItems}
							columns={brokerColumns}
							onRowClick={selectItem}
							selectedId={selectedItem?.broker_key}
							idField="broker_key"
						/>
					</div>
					<!-- Simple Pagination Controls -->
					{#if totalItems > pageSize}
						<div class="p-2 border-t flex justify-end gap-2">
							<Button
								variant="outline"
								size="sm"
								disabled={currentPage === 1}
								onclick={() => currentPage--}
							>
								Anterior
							</Button>
							<span class="flex items-center text-xs text-muted-foreground px-2">
								Página {currentPage} de {Math.ceil(totalItems / pageSize)}
							</span>
							<Button
								variant="outline"
								size="sm"
								disabled={currentPage * pageSize >= totalItems}
								onclick={() => currentPage++}
							>
								Siguiente
							</Button>
						</div>
					{/if}
				</div>
			</div>

			<!-- Right Panel: Details -->
			<div
				class="w-96 flex-none flex flex-col border rounded-xl bg-muted/30 shadow-sm overflow-hidden"
			>
				<div class="p-4 border-b bg-card">
					<p class="text-[10px] uppercase tracking-widest opacity-80 text-muted-foreground">
						Detalles del Agente
					</p>
					<h2
						class="text-xl font-black font-mono tracking-tighter truncate"
						title={selectedItem?.name || ''}
					>
						{selectedItem?.name || '---'}
					</h2>
					<div class="flex items-center gap-2 mt-1">
						<span class="text-xs font-mono text-muted-foreground"
							>Patente: {selectedItem?.broker_key || ''}</span
						>
					</div>
				</div>

				<div class="flex-1 overflow-auto p-5 space-y-6 bg-card">
					{#if selectedItem}
						<div class="grid grid-cols-1 gap-4">
							<div class="space-y-1">
								<Label
									class="text-[10px] uppercase text-muted-foreground font-bold flex items-center gap-1"
								>
									<FileText size={10} /> Licencia / Autorización
								</Label>
								<p class="text-sm font-medium">{selectedItem.license || '-'}</p>
							</div>

							{#if selectedItem.tax_id}
								<div class="space-y-1">
									<Label
										class="text-[10px] uppercase text-muted-foreground font-bold flex items-center gap-1"
									>
										<Hash size={10} /> RFC / Tax ID
									</Label>
									<p class="text-sm font-mono">{selectedItem.tax_id}</p>
								</div>
							{/if}

							<div class="pt-4 border-t space-y-3">
								<Label
									class="text-[10px] uppercase text-muted-foreground font-bold flex items-center gap-1"
								>
									<MapPin size={10} /> Dirección
								</Label>
								<div class="text-sm space-y-1">
									<p>{selectedItem.address || ''}</p>
									<p>
										{[selectedItem.city, selectedItem.state].filter(Boolean).join(', ')}
									</p>
									<p>
										{[selectedItem.postal_code, selectedItem.country].filter(Boolean).join(', ')}
									</p>
								</div>
							</div>

							<div class="pt-4 border-t space-y-3">
								<Label
									class="text-[10px] uppercase text-muted-foreground font-bold flex items-center gap-1"
								>
									<Phone size={10} /> Contacto
								</Label>
								{#if selectedItem.email}
									<div class="flex items-center gap-2 text-sm">
										<Mail size={14} class="text-muted-foreground" />
										<span>{selectedItem.email}</span>
									</div>
								{/if}
								{#if selectedItem.phone}
									<div class="flex items-center gap-2 text-sm">
										<Phone size={14} class="text-muted-foreground" />
										<span>{selectedItem.phone}</span>
									</div>
								{/if}
								{#if selectedItem.contact}
									<div class="mt-2 text-xs text-muted-foreground">
										<span class="font-bold">Contacto:</span>
										{selectedItem.contact}
									</div>
								{/if}
							</div>
						</div>
					{:else}
						<div
							class="flex flex-col items-center justify-center h-full text-center text-muted-foreground opacity-50"
						>
							<Building2 class="h-12 w-12 mb-3" />
							<p class="text-sm">Selecciona un agente</p>
						</div>
					{/if}
				</div>
			</div>
		</Tabs.Content>

		<Tabs.Content value="customs" class="flex-1 overflow-auto mt-0 data-[state=inactive]:hidden">
			<!-- Reusing DataTable from Customs Sections -->
			<Card.Root class="h-full flex flex-col border-none shadow-none">
				<Card.Content class="flex-1 p-0">
					<SectionsDataTable
						data={sections}
						columns={sectionsColumns}
						loading={loadingSections}
						hasMore={hasMoreSections}
						loadMore={loadMoreSections}
					/>
				</Card.Content>
			</Card.Root>
		</Tabs.Content>
	</Tabs.Root>
</div>
<div
	class="fixed bottom-0 left-0 right-0 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 border-t shadow-lg z-[5] group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] ml-[calc(var(--sidebar-width))]"
>
	<div class="px-4 py-4 max-w-[1400px] mx-auto">
		<div class="flex justify-end gap-2">
			{#if activeTab === 'brokers'}
				<Button size="sm" href="/dashboard/customs_brokers/edit">
					<Plus class="h-4 w-4 mr-1" />
					Nuevo
				</Button>
				<Button variant="outline" size="sm" onclick={handleEdit} disabled={!selectedItem}>
					Editar
				</Button>
				<Button
					variant="outline"
					size="sm"
					onclick={handleDelete}
					disabled={!selectedItem}
					class="text-destructive hover:text-destructive"
				>
					Borrar
				</Button>
			{:else}
				<Button size="sm" onclick={() => toast.info('Pendiente')}>
					<Plus class="h-4 w-4 mr-1" />
					Nueva Sección
				</Button>
			{/if}
		</div>
	</div>
</div>

<DeleteDialog bind:open={showDeleteDialog} broker={selectedItem} onSuccess={handleActionSuccess} />
