<script lang="ts">
	import { Receipt, 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 { quotesAPI, type Quote } from '$lib/api/crm';
	import { QUOTE_STATUS, labelOf, formatMoney } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

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

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

	const statusClass: Record<string, string> = {
		borrador: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400',
		enviada: 'bg-blue-100 text-blue-700 dark:bg-blue-950/40 dark:text-blue-400',
		aceptada: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400',
		rechazada: '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 quotesAPI.list(cid);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar las cotizaciones');
		} finally {
			loading = false;
		}
	}

	async function remove(q: Quote) {
		if (!companyId || !confirm(`¿Eliminar la cotización ${q.reference ?? q.id}?`)) return;
		try {
			await quotesAPI.remove(q.id, companyId);
			toast.success('Cotización eliminada');
			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"><Receipt class="h-6 w-6" /> Cotizaciones</h1>
			<p class="mt-1 text-sm text-muted-foreground">Propuestas económicas con conceptos de costo y venta.</p>
		</div>
		<Button href="/dashboard/crm/cotizaciones/nuevo" disabled={!companyId}><Plus class="mr-1 h-4 w-4" /> Nueva cotización</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…" bind:value={search} />
				</div>
				<select class={inputCls} bind:value={statusFilter}>
					<option value="">Todos los estatus</option>
					{#each QUOTE_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 cotizaciones.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Folio</Table.Head>
								<Table.Head>Solicitud</Table.Head>
								<Table.Head>Estatus</Table.Head>
								<Table.Head class="text-right">Total venta</Table.Head>
								<Table.Head class="text-right">Margen</Table.Head>
								<Table.Head class="text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each filtered as q (q.id)}
								<Table.Row>
									<Table.Cell class="font-medium"><a class="hover:underline" href={`/dashboard/crm/cotizaciones/${q.id}`}>{q.reference ?? `#${q.id}`}</a></Table.Cell>
									<Table.Cell>{#if q.service_request_id}<a class="text-sm hover:underline" href={`/dashboard/crm/solicitudes/${q.service_request_id}`}>{q.service_request_reference ?? `#${q.service_request_id}`}</a>{:else}<span class="text-sm text-muted-foreground">—</span>{/if}</Table.Cell>
									<Table.Cell><span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {statusClass[q.status] ?? ''}">{labelOf(QUOTE_STATUS, q.status)}</span></Table.Cell>
									<Table.Cell class="text-right">{formatMoney(q.total_sale, q.currency)}</Table.Cell>
									<Table.Cell class="text-right">{formatMoney(q.margin, q.currency)}</Table.Cell>
									<Table.Cell class="text-right">
										<Button variant="ghost" size="sm" href={`/dashboard/crm/cotizaciones/${q.id}`} aria-label="Abrir"><ChevronRight class="h-4 w-4" /></Button>
										<Button variant="ghost" size="sm" onclick={() => remove(q)} 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>
