<script lang="ts">
	import { Ship, Plus, Trash2, Search, ChevronRight } from '@lucide/svelte';
	import * as Card from '$lib/components/ui/card';
	import * as Table from '$lib/components/ui/table';
	import { Button } from '$lib/components/ui/button';
	import { companyStore } from '$lib/stores/company.svelte';
	import { shipmentsAPI, type Shipment } from '$lib/api/ops';
	import { SHIPMENT_STATUS, OPERATION_TYPES, TRANSPORT_MODES, labelOf, formatDate } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

	let items = $state<Shipment[]>([]);
	let loading = $state(false);
	let search = $state('');
	let statusFilter = $state('');

	const companyId = $derived(companyStore.activeCompany?.id ?? null);
	const filtered = $derived(
		items.filter((s) => {
			if (statusFilter && s.status !== statusFilter) return false;
			if (search.trim()) {
				const q = search.trim().toLowerCase();
				return `${s.reference ?? ''} ${s.booking_number ?? ''} ${s.origin ?? ''} ${s.destination ?? ''}`.toLowerCase().includes(q);
			}
			return true;
		})
	);

	const statusClass: Record<string, string> = {
		abierta: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400',
		booking: 'bg-blue-100 text-blue-700 dark:bg-blue-950/40 dark:text-blue-400',
		en_transito: 'bg-amber-100 text-amber-700 dark:bg-amber-950/40 dark:text-amber-400',
		arribado: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-950/40 dark:text-cyan-400',
		entregada: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400',
		cerrada: 'bg-slate-200 text-slate-700 dark:bg-slate-700 dark:text-slate-300',
		cancelada: 'bg-red-100 text-red-700 dark:bg-red-950/40 dark:text-red-400'
	};

	$effect(() => {
		const cid = companyId;
		if (!cid) return;
		void load(cid);
	});

	async function load(cid: number) {
		loading = true;
		try {
			items = await shipmentsAPI.list(cid);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar los embarques');
		} finally {
			loading = false;
		}
	}

	async function remove(s: Shipment) {
		if (!companyId || !confirm(`¿Eliminar el embarque ${s.reference ?? s.id}?`)) return;
		try {
			await shipmentsAPI.remove(s.id, companyId);
			toast.success('Embarque eliminado');
			await load(companyId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo eliminar');
		}
	}

	const inputCls = 'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';
</script>

<div class="space-y-6">
	<div class="flex flex-wrap items-center justify-between gap-3">
		<div>
			<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><Ship class="h-6 w-6" /> Embarques</h1>
			<p class="mt-1 text-sm text-muted-foreground">Operaciones logísticas: booking, Cut Off, documentos y seguimiento.</p>
		</div>
		<Button href="/dashboard/ops/embarques/nuevo" disabled={!companyId}><Plus class="mr-1 h-4 w-4" /> Nuevo embarque</Button>
	</div>

	<Card.Root>
		<Card.Header>
			<div class="flex flex-wrap items-center gap-3">
				<div class="relative max-w-sm flex-1">
					<Search class="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
					<input class="w-full py-2 pl-8 pr-3 {inputCls}" placeholder="Buscar por folio, booking o ruta…" bind:value={search} />
				</div>
				<select class={inputCls} bind:value={statusFilter}>
					<option value="">Todos los estatus</option>
					{#each SHIPMENT_STATUS as s (s.value)}<option value={s.value}>{s.label}</option>{/each}
				</select>
			</div>
		</Card.Header>
		<Card.Content>
			{#if loading}
				<p class="py-6 text-center text-sm text-muted-foreground">Cargando…</p>
			{:else if filtered.length === 0}
				<p class="py-6 text-center text-sm text-muted-foreground">Sin embarques.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Folio</Table.Head>
								<Table.Head>Operación</Table.Head>
								<Table.Head>Ruta</Table.Head>
								<Table.Head>ETD / ETA</Table.Head>
								<Table.Head>Estatus</Table.Head>
								<Table.Head class="text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each filtered as s (s.id)}
								<Table.Row>
									<Table.Cell class="font-medium"><a class="hover:underline" href={`/dashboard/ops/embarques/${s.id}`}>{s.reference ?? `#${s.id}`}</a>{#if s.booking_number}<span class="block text-xs text-muted-foreground">{s.booking_number}</span>{/if}</Table.Cell>
									<Table.Cell class="text-sm">{labelOf(OPERATION_TYPES, s.operation_type)} · {labelOf(TRANSPORT_MODES, s.transport_mode)}</Table.Cell>
									<Table.Cell class="text-sm">{[s.origin, s.destination].filter(Boolean).join(' → ') || '—'}</Table.Cell>
									<Table.Cell class="text-sm">{formatDate(s.etd)} / {formatDate(s.eta)}</Table.Cell>
									<Table.Cell><span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {statusClass[s.status] ?? ''}">{labelOf(SHIPMENT_STATUS, s.status)}</span></Table.Cell>
									<Table.Cell class="text-right">
										<Button variant="ghost" size="sm" href={`/dashboard/ops/embarques/${s.id}`} aria-label="Abrir"><ChevronRight class="h-4 w-4" /></Button>
										<Button variant="ghost" size="sm" onclick={() => remove(s)} aria-label="Eliminar"><Trash2 class="h-4 w-4 text-destructive" /></Button>
									</Table.Cell>
								</Table.Row>
							{/each}
						</Table.Body>
					</Table.Root>
				</div>
			{/if}
		</Card.Content>
	</Card.Root>
</div>
