<script lang="ts">
	import { Truck, Plus, Trash2, Search, Pencil } 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 { suppliersAPI, type Supplier } from '$lib/api/crm';
	import { SUPPLIER_CLASSIFICATIONS, COVERAGE, labelOf } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

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

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

	const filtered = $derived(
		search.trim()
			? items.filter((s) => `${s.name} ${s.trade_name ?? ''} ${s.rfc ?? ''}`.toLowerCase().includes(search.trim().toLowerCase()))
			: items
	);

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

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

	async function remove(s: Supplier) {
		if (!companyId) return;
		if (!confirm(`¿Eliminar "${s.name}"?`)) return;
		try {
			await suppliersAPI.remove(s.id, companyId);
			toast.success('Proveedor eliminado');
			await load(companyId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo eliminar');
		}
	}

	function classNames(s: Supplier): string {
		return (s.classifications ?? []).map((c) => labelOf(SUPPLIER_CLASSIFICATIONS, c)).join(', ') || '—';
	}

	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">
				<Truck class="h-6 w-6" />
				Proveedores
			</h1>
			<p class="mt-1 text-sm text-muted-foreground">Navieras, aerolíneas, transportistas, agentes y más.</p>
		</div>
		<Button href="/dashboard/crm/proveedores/nuevo" disabled={!companyId}>
			<Plus class="mr-1 h-4 w-4" /> Nuevo proveedor
		</Button>
	</div>

	<Card.Root>
		<Card.Header>
			<div class="relative max-w-sm">
				<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 nombre o RFC…" bind:value={search} />
			</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 proveedores registrados.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Razón social</Table.Head>
								<Table.Head>Clasificación</Table.Head>
								<Table.Head>Cobertura</Table.Head>
								<Table.Head>RFC</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/crm/proveedores/${s.id}`}>{s.name}</a>
										{#if s.trade_name}<span class="block text-xs text-muted-foreground">{s.trade_name}</span>{/if}
									</Table.Cell>
									<Table.Cell class="text-xs">{classNames(s)}</Table.Cell>
									<Table.Cell>{labelOf(COVERAGE, s.coverage)}</Table.Cell>
									<Table.Cell class="font-mono text-xs">{s.rfc ?? '—'}</Table.Cell>
									<Table.Cell class="text-right">
										<Button variant="ghost" size="sm" href={`/dashboard/crm/proveedores/${s.id}`}>
											<Pencil class="mr-1 h-4 w-4" /> Editar
										</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>
