<script lang="ts">
	import { Contact as ContactIcon, Plus, Pencil, Trash2, Search } 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 { contactsAPI, accountsAPI, suppliersAPI, type Contact, type ContactInput, type Account, type Supplier } from '$lib/api/crm';
	import { toast } from 'svelte-sonner';

	let items = $state<Contact[]>([]);
	let accounts = $state<Account[]>([]);
	let suppliers = $state<Supplier[]>([]);
	let loading = $state(false);
	let search = $state('');
	let modalOpen = $state(false);
	let saving = $state(false);
	let editingId = $state<number | null>(null);
	let form = $state<ContactInput>({ first_name: '', is_primary: false });

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

	// A quién pertenece el contacto: cliente/prospecto (cuenta) o proveedor
	function ownerLabel(c: Contact): { kind: string; name: string } | null {
		if (c.account_id) {
			const a = accounts.find((x) => x.id === c.account_id);
			const kind = a?.record_type === 'prospecto' ? 'Prospecto' : 'Cliente';
			return { kind, name: a?.name ?? `#${c.account_id}` };
		}
		if (c.supplier_id) {
			const s = suppliers.find((x) => x.id === c.supplier_id);
			return { kind: 'Proveedor', name: s?.name ?? `#${c.supplier_id}` };
		}
		return null;
	}

	const filtered = $derived(
		search.trim()
			? items.filter((c) =>
					`${c.first_name} ${c.last_name ?? ''} ${c.email ?? ''}`
						.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, accounts, suppliers] = await Promise.all([contactsAPI.list(cid), accountsAPI.list(cid), suppliersAPI.list(cid)]);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar los contactos');
		} finally {
			loading = false;
		}
	}

	function openCreate() {
		editingId = null;
		form = { first_name: '', is_primary: false };
		modalOpen = true;
	}

	function openEdit(c: Contact) {
		editingId = c.id;
		form = { ...c };
		modalOpen = true;
	}

	async function save(event: SubmitEvent) {
		event.preventDefault();
		if (!companyId) return;
		if (!form.first_name?.trim()) {
			toast.error('El nombre es obligatorio');
			return;
		}
		saving = true;
		try {
			const payload = { ...form, account_id: form.account_id ? Number(form.account_id) : null };
			if (editingId) {
				await contactsAPI.update(editingId, payload, companyId);
				toast.success('Contacto actualizado');
			} else {
				await contactsAPI.create(payload, companyId);
				toast.success('Contacto creado');
			}
			modalOpen = false;
			await load(companyId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo guardar el contacto');
		} finally {
			saving = false;
		}
	}

	async function remove(c: Contact) {
		if (!companyId) return;
		if (!confirm(`¿Eliminar el contacto "${c.first_name} ${c.last_name ?? ''}"?`)) return;
		try {
			await contactsAPI.remove(c.id, companyId);
			toast.success('Contacto eliminado');
			await load(companyId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo eliminar el contacto');
		}
	}
</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">
				<ContactIcon class="h-6 w-6" />
				Contactos
			</h1>
			<p class="mt-1 text-sm text-muted-foreground">Personas asociadas a tus cuentas.</p>
		</div>
		<Button onclick={openCreate} disabled={!companyId}>
			<Plus class="mr-1 h-4 w-4" /> Nuevo contacto
		</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 rounded-md border bg-transparent py-2 pl-8 pr-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
					placeholder="Buscar por nombre o email…"
					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 contactos registrados.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Nombre</Table.Head>
								<Table.Head>Pertenece a</Table.Head>
								<Table.Head>Puesto</Table.Head>
								<Table.Head>Email</Table.Head>
								<Table.Head>Teléfono</Table.Head>
								<Table.Head class="text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each filtered as c (c.id)}
								<Table.Row>
									<Table.Cell class="font-medium">
										{c.first_name} {c.last_name ?? ''}
										{#if c.is_primary}<span class="ml-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary">Principal</span>{/if}
									</Table.Cell>
									<Table.Cell>{#if ownerLabel(c)}{@const o = ownerLabel(c)}<span class="rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">{o?.kind}</span> <span>{o?.name}</span>{:else}—{/if}</Table.Cell>
									<Table.Cell>{c.job_title ?? '—'}</Table.Cell>
									<Table.Cell>{c.email ?? '—'}</Table.Cell>
									<Table.Cell>{c.phone ?? c.mobile ?? '—'}</Table.Cell>
									<Table.Cell class="text-right">
										<Button variant="ghost" size="sm" onclick={() => openEdit(c)} aria-label="Editar">
											<Pencil class="h-4 w-4" />
										</Button>
										<Button variant="ghost" size="sm" onclick={() => remove(c)} 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>

{#if modalOpen}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" role="presentation" onclick={() => (modalOpen = false)}>
		<div class="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-lg border bg-card p-6 shadow-lg" role="dialog" aria-modal="true" onclick={(e) => e.stopPropagation()}>
			<h2 class="mb-4 text-lg font-semibold">{editingId ? 'Editar contacto' : 'Nuevo contacto'}</h2>
			<form class="grid gap-4 sm:grid-cols-2" onsubmit={save}>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Nombre *</span>
					<input class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.first_name} required />
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Apellidos</span>
					<input class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.last_name} />
				</label>
				<label class="flex flex-col gap-1 text-sm sm:col-span-2">
					<span class="font-medium">Cuenta</span>
					<select class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.account_id}>
						<option value={null}>— Sin cuenta —</option>
						{#each accounts as a (a.id)}<option value={a.id}>{a.name}</option>{/each}
					</select>
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Puesto</span>
					<input class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.job_title} />
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Departamento</span>
					<input class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.department} />
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Email</span>
					<input type="email" class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.email} />
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Teléfono</span>
					<input class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.phone} />
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Móvil</span>
					<input class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.mobile} />
				</label>
				<label class="flex items-center gap-2 text-sm">
					<input type="checkbox" class="h-4 w-4 rounded border" bind:checked={form.is_primary} />
					<span class="font-medium">Contacto principal</span>
				</label>
				<label class="flex flex-col gap-1 text-sm sm:col-span-2">
					<span class="font-medium">Notas</span>
					<textarea rows="3" class="rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" bind:value={form.notes}></textarea>
				</label>
				<div class="flex justify-end gap-2 sm:col-span-2">
					<Button type="button" variant="outline" onclick={() => (modalOpen = false)}>Cancelar</Button>
					<Button type="submit" disabled={saving}>{saving ? 'Guardando…' : 'Guardar'}</Button>
				</div>
			</form>
		</div>
	</div>
{/if}
