<script lang="ts">
	import { UserPlus, Plus, Pencil, Trash2, Search, ArrowRightLeft } 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 { onMount } from 'svelte';
	import { leadsAPI, type Lead, type LeadInput } from '$lib/api/crm';
	import { LEAD_SOURCES, LEAD_STATUS, labelOf, formatMoney } from '$lib/components/crm/format';
	import { crmCatalogs } from '$lib/stores/crm-catalogs.svelte';
	import { toast } from 'svelte-sonner';

	onMount(() => void crmCatalogs.ensure('medio_contacto'));

	let items = $state<Lead[]>([]);
	let loading = $state(false);
	let search = $state('');
	let modalOpen = $state(false);
	let saving = $state(false);
	let editingId = $state<number | null>(null);
	let form = $state<LeadInput>({ name: '', status: 'new' });

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

	const filtered = $derived(
		search.trim()
			? items.filter((l) =>
					`${l.name} ${l.company_name ?? ''} ${l.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 = await leadsAPI.list(cid);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar los prospectos');
		} finally {
			loading = false;
		}
	}

	function openCreate() {
		editingId = null;
		form = { name: '', status: 'new' };
		modalOpen = true;
	}

	function openEdit(l: Lead) {
		editingId = l.id;
		form = { ...l };
		modalOpen = true;
	}

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

	async function convert(l: Lead) {
		if (!companyId) return;
		if (!confirm(`¿Convertir "${l.name}" en cuenta, contacto y oportunidad?`)) return;
		try {
			await leadsAPI.convert(l.id, { create_opportunity: true }, companyId);
			toast.success('Prospecto convertido');
			await load(companyId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo convertir el prospecto');
		}
	}

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

	const statusClass: Record<string, string> = {
		new: 'bg-blue-100 text-blue-700 dark:bg-blue-950/40 dark:text-blue-400',
		contacted: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-950/40 dark:text-cyan-400',
		qualified: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400',
		unqualified: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400',
		converted: 'bg-purple-100 text-purple-700 dark:bg-purple-950/40 dark:text-purple-400'
	};
</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">
				<UserPlus class="h-6 w-6" />
				Prospectos
			</h1>
			<p class="mt-1 text-sm text-muted-foreground">Leads sin calificar. Conviértelos cuando avancen.</p>
		</div>
		<Button onclick={openCreate} disabled={!companyId}>
			<Plus class="mr-1 h-4 w-4" /> Nuevo prospecto
		</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 empresa…"
					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 prospectos registrados.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Nombre</Table.Head>
								<Table.Head>Empresa</Table.Head>
								<Table.Head>Origen</Table.Head>
								<Table.Head>Estado</Table.Head>
								<Table.Head class="text-right">Valor est.</Table.Head>
								<Table.Head class="text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each filtered as l (l.id)}
								<Table.Row>
									<Table.Cell class="font-medium">
										{l.name}
										{#if l.contact_name}<span class="block text-xs text-muted-foreground">{l.contact_name}</span>{/if}
									</Table.Cell>
									<Table.Cell>{l.company_name ?? '—'}</Table.Cell>
									<Table.Cell>{labelOf(LEAD_SOURCES, l.source)}</Table.Cell>
									<Table.Cell>
										<span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {statusClass[l.status] ?? ''}">
											{labelOf(LEAD_STATUS, l.status)}
										</span>
									</Table.Cell>
									<Table.Cell class="text-right">{formatMoney(l.estimated_value)}</Table.Cell>
									<Table.Cell class="text-right">
										<Button
											variant="ghost"
											size="sm"
											onclick={() => convert(l)}
											disabled={l.status === 'converted'}
											aria-label="Convertir"
											title="Convertir a cuenta/contacto/oportunidad"
										>
											<ArrowRightLeft class="h-4 w-4 text-primary" />
										</Button>
										<Button variant="ghost" size="sm" onclick={() => openEdit(l)} aria-label="Editar">
											<Pencil class="h-4 w-4" />
										</Button>
										<Button variant="ghost" size="sm" onclick={() => remove(l)} 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 prospecto' : 'Nuevo prospecto'}</h2>
			<form class="grid gap-4 sm:grid-cols-2" onsubmit={save}>
				<label class="flex flex-col gap-1 text-sm sm:col-span-2">
					<span class="font-medium">Nombre / título *</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.name} required />
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Empresa</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.company_name} />
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Nombre de contacto</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.contact_name} />
				</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">Origen</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.source}>
						<option value={undefined}>—</option>
						{#each LEAD_SOURCES as s (s.value)}<option value={s.value}>{s.label}</option>{/each}
					</select>
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Medio de contacto preferido</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.preferred_contact_method}>
						<option value={undefined}>—</option>
						{#each crmCatalogs.options('medio_contacto') as m (m.value)}<option value={m.value}>{m.label}</option>{/each}
					</select>
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Estado</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.status}>
						{#each LEAD_STATUS as s (s.value)}<option value={s.value}>{s.label}</option>{/each}
					</select>
				</label>
				<label class="flex flex-col gap-1 text-sm">
					<span class="font-medium">Valor estimado (MXN)</span>
					<input type="number" min="0" step="0.01" 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.estimated_value} />
				</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}
