<script lang="ts">
	import { FileText, 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 { serviceRequestsAPI, accountsAPI, type ServiceRequest, type Account } from '$lib/api/crm';
	import { OPERATION_TYPES, SR_STATUS, TRANSPORT_MODES, labelOf } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

	let items = $state<ServiceRequest[]>([]);
	let accounts = $state<Account[]>([]);
	let loading = $state(false);
	let search = $state('');
	let statusFilter = $state('');
	let clientFilter = $state('');

	const companyId = $derived(companyStore.activeCompany?.id ?? null);
	function accountName(id: number | null): string {
		return accounts.find((a) => a.id === id)?.name ?? '—';
	}
	const filtered = $derived(
		items.filter((r) => {
			if (statusFilter && r.status !== statusFilter) return false;
			if (clientFilter && String(r.account_id ?? '') !== clientFilter) return false;
			if (search.trim()) {
				const q = search.trim().toLowerCase();
				return `${r.reference ?? ''} ${r.origin ?? ''} ${r.destination ?? ''} ${accountName(r.account_id)}`.toLowerCase().includes(q);
			}
			return true;
		})
	);

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

	async function load(cid: number) {
		loading = true;
		try {
			[items, accounts] = await Promise.all([serviceRequestsAPI.list(cid), accountsAPI.list(cid)]);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar las solicitudes');
		} finally {
			loading = false;
		}
	}

	async function remove(r: ServiceRequest) {
		if (!companyId || !confirm(`¿Eliminar la solicitud ${r.reference ?? r.id}?`)) return;
		try {
			await serviceRequestsAPI.remove(r.id, companyId);
			toast.success('Solicitud 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"><FileText class="h-6 w-6" /> Solicitudes de servicio</h1>
			<p class="mt-1 text-sm text-muted-foreground">Levantamiento de requerimientos (RFQ) para cotizar.</p>
		</div>
		<Button href="/dashboard/crm/solicitudes/nuevo" disabled={!companyId}><Plus class="mr-1 h-4 w-4" /> Nueva solicitud</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 o ruta…" bind:value={search} />
				</div>
				<select class={inputCls} bind:value={statusFilter}>
					<option value="">Todos los estatus</option>
					{#each SR_STATUS as s (s.value)}<option value={s.value}>{s.label}</option>{/each}
				</select>
				<select class={inputCls} bind:value={clientFilter}>
					<option value="">Todos los clientes</option>
					{#each accounts as a (a.id)}<option value={String(a.id)}>{a.name}</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 solicitudes.</p>
			{:else}
				<div class="overflow-x-auto">
					<Table.Root>
						<Table.Header>
							<Table.Row>
								<Table.Head>Folio</Table.Head>
								<Table.Head>Cliente</Table.Head>
								<Table.Head>Operación</Table.Head>
								<Table.Head>Medio</Table.Head>
								<Table.Head>Ruta</Table.Head>
								<Table.Head>Estatus</Table.Head>
								<Table.Head class="text-right">Acciones</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#each filtered as r (r.id)}
								<Table.Row>
									<Table.Cell class="font-medium"><a class="hover:underline" href={`/dashboard/crm/solicitudes/${r.id}`}>{r.reference ?? `#${r.id}`}</a></Table.Cell>
									<Table.Cell>{accountName(r.account_id)}</Table.Cell>
									<Table.Cell>{labelOf(OPERATION_TYPES, r.operation_type)}</Table.Cell>
									<Table.Cell>{labelOf(TRANSPORT_MODES, r.transport_mode)}</Table.Cell>
									<Table.Cell class="text-sm">{[r.origin, r.destination].filter(Boolean).join(' → ') || '—'}</Table.Cell>
									<Table.Cell>{labelOf(SR_STATUS, r.status)}</Table.Cell>
									<Table.Cell class="text-right">
										<Button variant="ghost" size="sm" href={`/dashboard/crm/solicitudes/${r.id}`} aria-label="Abrir"><ChevronRight class="h-4 w-4" /></Button>
										<Button variant="ghost" size="sm" onclick={() => remove(r)} 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>
