<script lang="ts">
	import { Building2, 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 { accountsAPI, type Account } from '$lib/api/crm';
	import { ACCOUNT_STATUS, RECORD_TYPES, COMMERCIAL_CLASSIFICATION, labelOf } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

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

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

	const filtered = $derived(
		items.filter((a) => {
			if (recordFilter && a.record_type !== recordFilter) return false;
			if (search.trim()) {
				const q = search.trim().toLowerCase();
				return `${a.name} ${a.trade_name ?? ''} ${a.rfc ?? ''}`.toLowerCase().includes(q);
			}
			return true;
		})
	);

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

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

	async function remove(a: Account) {
		if (!companyId) return;
		if (!confirm(`¿Eliminar "${a.name}"?`)) return;
		try {
			await accountsAPI.remove(a.id, companyId);
			toast.success('Cliente 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">
				<Building2 class="h-6 w-6" />
				Clientes / Prospectos
			</h1>
			<p class="mt-1 text-sm text-muted-foreground">Catálogo de clientes y prospectos.</p>
		</div>
		<Button href="/dashboard/crm/cuentas/nuevo" disabled={!companyId}>
			<Plus class="mr-1 h-4 w-4" /> Nuevo registro
		</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 nombre o RFC…" bind:value={search} />
				</div>
				<select class={inputCls} bind:value={recordFilter}>
					<option value="">Todos</option>
					{#each RECORD_TYPES as r (r.value)}<option value={r.value}>{r.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 registros.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Razón social</Table.Head>
								<Table.Head>Tipo</Table.Head>
								<Table.Head>RFC</Table.Head>
								<Table.Head>Clasificación</Table.Head>
								<Table.Head>Estatus</Table.Head>
								<Table.Head class="text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each filtered as a (a.id)}
								<Table.Row>
									<Table.Cell class="font-medium">
										<a class="hover:underline" href={`/dashboard/crm/cuentas/${a.id}`}>{a.name}</a>
										{#if a.trade_name}<span class="block text-xs text-muted-foreground">{a.trade_name}</span>{/if}
									</Table.Cell>
									<Table.Cell>
										<span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {a.record_type === 'cliente' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400' : 'bg-amber-100 text-amber-700 dark:bg-amber-950/40 dark:text-amber-400'}">
											{labelOf(RECORD_TYPES, a.record_type)}
										</span>
									</Table.Cell>
									<Table.Cell class="font-mono text-xs">{a.rfc ?? '—'}</Table.Cell>
									<Table.Cell>{labelOf(COMMERCIAL_CLASSIFICATION, a.commercial_classification)}</Table.Cell>
									<Table.Cell>{labelOf(ACCOUNT_STATUS, a.status)}</Table.Cell>
									<Table.Cell class="text-right">
										<Button variant="ghost" size="sm" href={`/dashboard/crm/cuentas/${a.id}`}>
											<Pencil class="mr-1 h-4 w-4" /> Editar
										</Button>
										<Button variant="ghost" size="sm" onclick={() => remove(a)} 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>
