<script lang="ts">
	import { ArrowLeft, FileText, Plus, Trash2, Receipt } from '@lucide/svelte';
	import { page } from '$app/state';
	import { goto } from '$app/navigation';
	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, rateRequestsAPI, quotesAPI, accountsAPI, suppliersAPI, contactsAPI,
		type ServiceRequest, type ServiceRequestInput, type RateRequest, type RateRequestInput,
		type Account, type Supplier, type Contact
	} from '$lib/api/crm';
	import {
		OPERATION_TYPES, SR_STATUS, SR_FORM_TABS,
		QUOTE_CONCEPTS, RATE_STATUS, labelOf
	} from '$lib/components/crm/format';
	import ServiceRequestFields from '$lib/components/crm/ServiceRequestFields.svelte';
	import { toast } from 'svelte-sonner';

	const srId = $derived(Number(page.params.id));
	const companyId = $derived(companyStore.activeCompany?.id ?? null);

	// Pestañas del formulario + la de tarifas
	const TABS = [...SR_FORM_TABS, { value: 'tarifas', label: 'Tarifas' }];

	let sr = $state<ServiceRequest | null>(null);
	let form = $state<ServiceRequestInput>({ operation_type: 'exportacion', additional_services: [] });
	let accounts = $state<Account[]>([]);
	let suppliers = $state<Supplier[]>([]);
	let contacts = $state<Contact[]>([]);
	let rates = $state<RateRequest[]>([]);
	let tab = $state('datos');
	let loading = $state(false);
	let saving = $state(false);
	let busy = $state(false);
	let adding = $state(false);
	let newRate = $state<RateRequestInput>({ service_request_id: 0, concept: 'flete_internacional', status: 'solicitada' });

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

	async function load(cid: number, id: number) {
		loading = true;
		try {
			[sr, accounts, suppliers, contacts, rates] = await Promise.all([
				serviceRequestsAPI.get(id, cid),
				accountsAPI.list(cid),
				suppliersAPI.list(cid),
				contactsAPI.list(cid),
				rateRequestsAPI.list(cid, id)
			]);
			form = { ...sr, additional_services: sr.additional_services ?? [], additional_service_costs: sr.additional_service_costs ?? {} };
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo cargar la solicitud');
		} finally {
			loading = false;
		}
	}

	async function save() {
		if (!companyId || !sr) return;
		saving = true;
		try {
			sr = await serviceRequestsAPI.update(sr.id, form, companyId);
			form = { ...sr, additional_services: sr.additional_services ?? [], additional_service_costs: sr.additional_service_costs ?? {} };
			toast.success('Cambios guardados');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo guardar');
		} finally {
			saving = false;
		}
	}

	async function registerContact() {
		if (!companyId || !sr) return;
		const notes = window.prompt('Nota del contacto al cliente (opcional):') ?? null;
		busy = true;
		try {
			sr = await serviceRequestsAPI.registerContact(sr.id, companyId, notes);
			form = { ...sr, additional_services: sr.additional_services ?? [], additional_service_costs: sr.additional_service_costs ?? {} };
			toast.success('Contacto registrado');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo registrar el contacto');
		} finally {
			busy = false;
		}
	}

	async function requote() {
		if (!companyId || !sr) return;
		busy = true;
		try {
			sr = await serviceRequestsAPI.requote(sr.id, companyId);
			form = { ...sr, additional_services: sr.additional_services ?? [], additional_service_costs: sr.additional_service_costs ?? {} };
			toast.success('Solicitud reabierta para re-cotizar');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo reabrir');
		} finally {
			busy = false;
		}
	}

	async function cotizar() {
		if (!companyId || !sr) return;
		if (!sr.account_id) { toast.error('Asigna un cliente antes de cotizar'); return; }
		busy = true;
		try {
			const quotes = await quotesAPI.fromServiceRequest(sr.id, companyId);
			toast.success(quotes.length > 1 ? `${quotes.length} cotizaciones generadas (FCL y LCL)` : 'Cotización generada');
			await goto(`/dashboard/crm/cotizaciones/${quotes[0].id}`);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo cotizar');
		} finally {
			busy = false;
		}
	}

	function startAdd() {
		newRate = { service_request_id: srId, concept: 'flete_internacional', status: 'solicitada', currency: 'USD' };
		adding = true;
	}

	async function saveRate() {
		if (!companyId) return;
		try {
			await rateRequestsAPI.create({ ...newRate, service_request_id: srId }, companyId);
			toast.success('Tarifa agregada');
			adding = false;
			rates = await rateRequestsAPI.list(companyId, srId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo agregar');
		}
	}

	async function removeRate(r: RateRequest) {
		if (!companyId || !confirm('¿Eliminar tarifa?')) return;
		await rateRequestsAPI.remove(r.id, companyId);
		rates = await rateRequestsAPI.list(companyId, srId);
	}

	function supplierName(id: number | null): string {
		return suppliers.find((s) => s.id === id)?.name ?? '—';
	}

	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">
	<Button variant="ghost" size="sm" href="/dashboard/crm/solicitudes"><ArrowLeft class="mr-1 h-4 w-4" /> Solicitudes</Button>

	{#if loading && !sr}
		<p class="text-sm text-muted-foreground">Cargando…</p>
	{:else if sr}
		<div class="flex flex-wrap items-start justify-between gap-3">
			<div>
				<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><FileText class="h-6 w-6" /> {sr.reference ?? `Solicitud #${sr.id}`}</h1>
				<p class="mt-1 text-sm text-muted-foreground">{labelOf(OPERATION_TYPES, sr.operation_type)} · {labelOf(SR_STATUS, sr.status)}</p>
				{#if sr.case_id}<a class="mt-1 inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 font-mono text-[11px] hover:underline" href={`/dashboard/crm/expedientes/${sr.case_id}`}>📁 Expediente</a>{/if}
			</div>
			<div class="flex flex-wrap gap-2">
				{#if sr.status === 'nueva' || sr.status === 'contacto'}<Button size="sm" variant="outline" onclick={registerContact} disabled={busy}>Registrar contacto</Button>{/if}
				{#if sr.status === 'rechazada' || sr.status === 'cotizada'}<Button size="sm" variant="outline" onclick={requote} disabled={busy}>Re-cotizar</Button>{/if}
				{#if sr.account_id && sr.status !== 'liberada'}<Button size="sm" onclick={cotizar} disabled={busy}><Receipt class="mr-1 h-4 w-4" /> Cotizar</Button>{/if}
			</div>
		</div>
		{#if sr.first_contact_at}<p class="text-xs text-muted-foreground">Contacto registrado{#if sr.first_contact_notes}: {sr.first_contact_notes}{/if}</p>{/if}

		<Card.Root>
			<Card.Content class="pt-6">
				<div class="mb-5 flex flex-wrap gap-1 border-b">
					{#each TABS as t (t.value)}
						<button type="button" class="border-b-2 px-3 py-2 text-sm font-medium transition-colors {tab === t.value ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}" onclick={() => (tab = t.value)}>{t.label}</button>
					{/each}
				</div>

				{#if tab === 'tarifas'}
					<div class="mb-3 flex justify-end"><Button size="sm" variant="outline" onclick={startAdd}><Plus class="mr-1 h-4 w-4" /> Agregar tarifa</Button></div>
					{#if adding}
						<div class="mb-4 grid gap-3 rounded-md border p-3 sm:grid-cols-2">
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Concepto</span><select class={inputCls} bind:value={newRate.concept}>{#each QUOTE_CONCEPTS as c (c.value)}<option value={c.value}>{c.label}</option>{/each}</select></label>
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Proveedor</span><select class={inputCls} bind:value={newRate.supplier_id}><option value={undefined}>—</option>{#each suppliers as s (s.id)}<option value={s.id}>{s.name}</option>{/each}</select></label>
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tarifa</span><input type="number" min="0" step="0.01" class={inputCls} bind:value={newRate.rate_amount} /></label>
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Moneda</span><input class={inputCls} maxlength="3" bind:value={newRate.currency} /></label>
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Estatus</span><select class={inputCls} bind:value={newRate.status}>{#each RATE_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">Válida hasta</span><input type="date" class={inputCls} bind:value={newRate.valid_until} /></label>
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Descripción</span><input class={inputCls} bind:value={newRate.description} /></label>
							<div class="flex justify-end gap-2 sm:col-span-2"><Button variant="outline" size="sm" onclick={() => (adding = false)}>Cancelar</Button><Button size="sm" onclick={saveRate}>Guardar</Button></div>
						</div>
					{/if}
					{#if rates.length === 0}
						<p class="text-sm text-muted-foreground">Sin solicitudes de tarifa. Captúralas para sembrar los conceptos de la cotización.</p>
					{:else}
						<Table.Root>
							<Table.Header><Table.Row><Table.Head>Concepto</Table.Head><Table.Head>Proveedor</Table.Head><Table.Head class="text-right">Tarifa</Table.Head><Table.Head>Estatus</Table.Head><Table.Head></Table.Head></Table.Row></Table.Header>
							<Table.Body>
								{#each rates as r (r.id)}
									<Table.Row>
										<Table.Cell>{labelOf(QUOTE_CONCEPTS, r.concept)}</Table.Cell>
										<Table.Cell>{supplierName(r.supplier_id)}</Table.Cell>
										<Table.Cell class="text-right">{r.rate_amount != null ? `${r.rate_amount} ${r.currency ?? ''}` : '—'}</Table.Cell>
										<Table.Cell>{labelOf(RATE_STATUS, r.status)}</Table.Cell>
										<Table.Cell class="text-right"><Button variant="ghost" size="sm" onclick={() => removeRate(r)} aria-label="Eliminar"><Trash2 class="h-4 w-4 text-destructive" /></Button></Table.Cell>
									</Table.Row>
								{/each}
							</Table.Body>
						</Table.Root>
					{/if}
				{:else}
					<ServiceRequestFields bind:form {tab} {accounts} {contacts} {suppliers} />
					<div class="mt-6 flex justify-end border-t pt-4"><Button onclick={save} disabled={saving}>{saving ? 'Guardando…' : 'Guardar cambios'}</Button></div>
				{/if}
			</Card.Content>
		</Card.Root>
	{/if}
</div>
