<script lang="ts">
	import { ArrowLeft, Truck } from '@lucide/svelte';
	import { page } from '$app/state';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import SupplierFields from '$lib/components/crm/SupplierFields.svelte';
	import RelatedManager from '$lib/components/crm/RelatedManager.svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import { suppliersAPI, type Supplier, type SupplierInput } from '$lib/api/crm';
	import { COVERAGE, ACCOUNT_STATUS, labelOf, formatDate } from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

	type TabDef = { id: string; label: string; kind: 'info' | 'related'; section?: 'addresses' | 'contacts' | 'documents' };
	const TABS: TabDef[] = [
		{ id: 'generales', label: 'Datos generales', kind: 'info' },
		{ id: 'comercial', label: 'Comercial', kind: 'info' },
		{ id: 'fiscal', label: 'Fiscal', kind: 'info' },
		{ id: 'observaciones', label: 'Observaciones', kind: 'info' },
		{ id: 'direcciones', label: 'Direcciones', kind: 'related', section: 'addresses' },
		{ id: 'contactos', label: 'Contactos', kind: 'related', section: 'contacts' },
		{ id: 'documentos', label: 'Documentos', kind: 'related', section: 'documents' }
	];

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

	let supplier = $state<Supplier | null>(null);
	let form = $state<SupplierInput>({ name: '', classifications: [] });
	let countriesStr = $state('');
	let portsStr = $state('');
	let airportsStr = $state('');
	let customsStr = $state('');
	let tab = $state('generales');
	let loading = $state(false);
	let saving = $state(false);

	const activeTab = $derived(TABS.find((t) => t.id === tab) ?? TABS[0]);
	const toArr = (s: string): string[] => s.split(',').map((t) => t.trim()).filter(Boolean);
	const toStr = (a: string[] | null | undefined): string => (a ?? []).join(', ');

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

	function hydrate(s: Supplier) {
		form = { ...s, classifications: [...(s.classifications ?? [])] };
		countriesStr = toStr(s.countries);
		portsStr = toStr(s.ports);
		airportsStr = toStr(s.airports);
		customsStr = toStr(s.customs);
	}

	async function load(cid: number, id: number) {
		loading = true;
		try {
			supplier = await suppliersAPI.get(id, cid);
			hydrate(supplier);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo cargar el proveedor');
		} finally {
			loading = false;
		}
	}

	async function save() {
		if (!companyId || !supplier) return;
		if (!form.name?.trim()) {
			toast.error('La razón social es obligatoria');
			return;
		}
		saving = true;
		try {
			const payload: SupplierInput = {
				...form,
				countries: toArr(countriesStr),
				ports: toArr(portsStr),
				airports: toArr(airportsStr),
				customs: toArr(customsStr)
			};
			supplier = await suppliersAPI.update(supplier.id, payload, companyId);
			hydrate(supplier);
			toast.success('Cambios guardados');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron guardar los cambios');
		} finally {
			saving = false;
		}
	}
</script>

<div class="space-y-6">
	<Button variant="ghost" size="sm" href="/dashboard/crm/proveedores"><ArrowLeft class="mr-1 h-4 w-4" /> Proveedores</Button>

	{#if loading && !supplier}
		<p class="text-sm text-muted-foreground">Cargando…</p>
	{:else if supplier}
		<div>
			<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
				<Truck class="h-6 w-6" />
				{supplier.name}
			</h1>
			<p class="mt-1 text-sm text-muted-foreground">
				{labelOf(COVERAGE, supplier.coverage)} · {labelOf(ACCOUNT_STATUS, supplier.status)}
				{#if supplier.rfc}· <span class="font-mono">{supplier.rfc}</span>{/if}<br /><span class="text-xs">ID #{supplier.id} · Alta {formatDate(supplier.created_at)}{#if supplier.created_by} por <span class="font-mono">{supplier.created_by}</span>{/if} · Últ. modificación {formatDate(supplier.updated_at)}{#if supplier.updated_by} por <span class="font-mono">{supplier.updated_by}</span>{/if}</span>
			</p>
		</div>

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

				{#if activeTab.kind === 'info'}
					<SupplierFields bind:form {tab} bind:countriesStr bind:portsStr bind:airportsStr bind:customsStr />
					<div class="mt-6 flex justify-end border-t pt-4">
						<Button onclick={save} disabled={saving}>{saving ? 'Guardando…' : 'Guardar cambios'}</Button>
					</div>
				{:else if activeTab.section}
					<RelatedManager ownerType="supplier" ownerId={supplier.id} section={activeTab.section} />
				{/if}
			</Card.Content>
		</Card.Root>
	{/if}
</div>
