<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 { currentUser } from '$lib/auth';
	import {
		canViewCustomsBrokers,
		canCreateCustomsBrokers,
		canEditCustomsBrokers,
		canDeleteCustomsBrokers
	} from '$lib/permissions/customs-broker-permissions';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	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';
	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);
	const canViewBrokerList = $derived(canViewCustomsBrokers($currentUser));
	const canCreateBroker = $derived(canCreateCustomsBrokers($currentUser));
	const canEditBroker = $derived(canEditCustomsBrokers($currentUser));
	const canDeleteBroker = $derived(canDeleteCustomsBrokers($currentUser));

	// --- 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 handleRowDoubleClick(item: CustomsBroker) {
		if (!canEditBroker) {
			toast.error('No tienes permiso para editar agentes aduanales');
			return;
		}
		selectedItem = item;
		goto(`/dashboard/customs_brokers/edit/${item.broker_key}`);
	}
	function handleEdit() {
		if (!canEditBroker) {
			toast.error('No tienes permiso para editar agentes aduanales');
			return;
		}
		if (selectedItem) goto(`/dashboard/customs_brokers/edit/${selectedItem.broker_key}`);
	}
	async function handleDelete() {
		if (!canDeleteBroker) {
			toast.error('No tienes permiso para borrar agentes aduanales');
			return;
		}
		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') {
					if (!canCreateBroker) {
						toast.error('No tienes permiso para crear agentes aduanales');
						return;
					}
					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>

{#if !canViewBrokerList}
	<div
		class="flex h-[calc(100svh-4rem)] flex-col p-6 group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)]"
	>
		<ErrorState status={403} />
	</div>
{:else}
<div class="flex flex-col gap-6 p-6 h-[calc(100svh-4rem)] group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)] overflow-hidden">
	<div class="flex-none flex items-center justify-between">
		<div class="space-y-1">
			<h1 class="text-2xl font-bold tracking-tight">Gestión Aduanal</h1>
			<p class="text-muted-foreground">Administración de Agentes y Secciones Aduanales</p>
		</div>
	</div>

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

		<Tabs.Content
			value="brokers"
			class="mt-0 flex flex-1 gap-4 overflow-hidden data-[state=inactive]:hidden"
		>
			<div class="flex min-h-0 flex-1 flex-col gap-4 overflow-hidden">
				<div class="rounded-md border bg-background">
					<div class="space-y-4 p-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 bg-card"
									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 bg-card"
									oninput={handleSearch}
								/>
							</div>
							<div class="flex items-end"></div>
						</div>
					</div>
				</div>

				<div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border bg-background">
					<div class="flex items-center justify-between border-b bg-background/95 p-3">
						<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="mr-2 h-4 w-4" />
								Actualizar
							</Button>
						</div>
					</div>

					<div class="flex-1 overflow-auto bg-background">
						<BrokerDataTable
							data={paginatedItems}
							columns={brokerColumns}
							onRowClick={selectItem}
							onRowDoubleClick={handleRowDoubleClick}
							selectedId={selectedItem?.broker_key}
							idField="broker_key"
						/>
					</div>
					{#if totalItems > pageSize}
						<div class="flex justify-end gap-2 border-t p-2">
							<Button
								variant="outline"
								size="sm"
								disabled={currentPage === 1}
								onclick={() => currentPage--}
							>
								Anterior
							</Button>
							<span class="flex items-center px-2 text-xs text-muted-foreground">
								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>

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

				<div class="flex-1 space-y-6 overflow-auto bg-card p-5">
					{#if selectedItem}
						<div class="grid grid-cols-1 gap-4">
							<div class="space-y-1">
								<Label
									class="flex items-center gap-1 text-[10px] font-bold text-muted-foreground uppercase"
								>
									<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="flex items-center gap-1 text-[10px] font-bold text-muted-foreground uppercase"
									>
										<Hash size={10} /> RFC / Tax ID
									</Label>
									<p class="font-mono text-sm">{selectedItem.tax_id}</p>
								</div>
							{/if}

							<div class="space-y-3 border-t pt-4">
								<Label
									class="flex items-center gap-1 text-[10px] font-bold text-muted-foreground uppercase"
								>
									<MapPin size={10} /> Dirección
								</Label>
								<div class="space-y-1 text-sm">
									<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="space-y-3 border-t pt-4">
								<Label
									class="flex items-center gap-1 text-[10px] font-bold text-muted-foreground uppercase"
								>
									<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 h-full flex-col items-center justify-center text-center text-muted-foreground opacity-50"
						>
							<Building2 class="mb-3 h-12 w-12" />
							<p class="text-sm">Selecciona un agente</p>
						</div>
					{/if}
				</div>
			</div>
		</Tabs.Content>

		<Tabs.Content value="customs" class="mt-0 flex-1 overflow-auto data-[state=inactive]:hidden">
			<Card.Root class="flex h-full 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 class="h-20"></div>
</div>
<div
	class="fixed right-0 bottom-0 left-0 z-[5] ml-[calc(var(--sidebar-width))] border-t bg-background/95 shadow-lg backdrop-blur group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] supports-[backdrop-filter]:bg-background/80"
>
	<div class="mx-auto max-w-[1400px] px-4 py-4">
		<div class="flex justify-end gap-2">
			{#if activeTab === 'brokers'}
				{#if canCreateBroker}
					<Button size="sm" href="/dashboard/customs_brokers/edit/new">
						<Plus class="mr-1 h-4 w-4" />
						Nuevo
					</Button>
				{/if}
				{#if canEditBroker}
					<Button
						variant="outline"
						size="sm"
						onclick={handleEdit}
						disabled={!selectedItem}
					>
						Editar
					</Button>
				{/if}
				{#if canDeleteBroker}
					<Button
						variant="outline"
						size="sm"
						onclick={handleDelete}
						disabled={!selectedItem}
						class="text-destructive hover:text-destructive"
					>
						Borrar
					</Button>
				{/if}
			{:else}
				<Button size="sm" onclick={() => toast.info('Pendiente')}>
					<Plus class="mr-1 h-4 w-4" />
					Nueva Sección
				</Button>
			{/if}
		</div>
	</div>
</div>
{/if}

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