<script lang="ts">
	import { ArrowLeft, Building2 } from '@lucide/svelte';
	import { page } from '$app/state';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import AccountFields from '$lib/components/crm/AccountFields.svelte';
	import RelatedManager from '$lib/components/crm/RelatedManager.svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import { accountsAPI, type Account, type AccountInput } from '$lib/api/crm';
	import { RECORD_TYPES, 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 accountId = $derived(Number(page.params.id));
	const companyId = $derived(companyStore.activeCompany?.id ?? null);

	let account = $state<Account | null>(null);
	let form = $state<AccountInput>({ name: '' });
	let tab = $state('generales');
	let loading = $state(false);
	let saving = $state(false);

	const activeTab = $derived(TABS.find((t) => t.id === tab) ?? TABS[0]);

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

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

	async function save() {
		if (!companyId || !account) return;
		if (!form.name?.trim()) {
			toast.error('La razón social es obligatoria');
			return;
		}
		saving = true;
		try {
			account = await accountsAPI.update(account.id, form, companyId);
			form = { ...account };
			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/cuentas"><ArrowLeft class="mr-1 h-4 w-4" /> Clientes</Button>

	{#if loading && !account}
		<p class="text-sm text-muted-foreground">Cargando…</p>
	{:else if account}
		<div class="flex flex-wrap items-center justify-between gap-2">
			<div>
				<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
					<Building2 class="h-6 w-6" />
					{account.name}
				</h1>
				<p class="mt-1 text-sm text-muted-foreground">
					{labelOf(RECORD_TYPES, account.record_type)} · {labelOf(ACCOUNT_STATUS, account.status)}
					{#if account.rfc}· <span class="font-mono">{account.rfc}</span>{/if}
				</p>
				<p class="mt-1 text-xs text-muted-foreground">
					ID #{account.id} · Creado {formatDate(account.created_at)}{#if account.created_by} por <span class="font-mono">{account.created_by}</span>{/if}
					· Últ. actualización {formatDate(account.updated_at)}{#if account.updated_by} por <span class="font-mono">{account.updated_by}</span>{/if}
				</p>
			</div>
		</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'}
					<AccountFields bind:form tab={tab} {companyId} />
					<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="account" ownerId={account.id} section={activeTab.section} />
				{/if}
			</Card.Content>
		</Card.Root>
	{/if}
</div>
