<script lang="ts">
	import { ArrowLeft, Building2 } from '@lucide/svelte';
	import { goto } from '$app/navigation';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import AccountFields from '$lib/components/crm/AccountFields.svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import { accountsAPI, type AccountInput } from '$lib/api/crm';
	import { toast } from 'svelte-sonner';

	const TABS = [
		{ id: 'generales', label: 'Datos generales' },
		{ id: 'comercial', label: 'Comercial' },
		{ id: 'fiscal', label: 'Fiscal' },
		{ id: 'observaciones', label: 'Observaciones' }
	];

	let form = $state<AccountInput>({ name: '', record_type: 'cliente', status: 'active', country: 'MX' });
	let tab = $state('generales');
	let saving = $state(false);

	const companyId = $derived(companyStore.activeCompany?.id ?? null);

	async function save() {
		if (!companyId) return;
		if (!form.name?.trim()) {
			toast.error('La razón social es obligatoria');
			tab = 'generales';
			return;
		}
		saving = true;
		try {
			const created = await accountsAPI.create(form, companyId);
			toast.success('Cliente creado');
			await goto(`/dashboard/crm/cuentas/${created.id}`);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo crear el cliente');
		} 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>

	<div>
		<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
			<Building2 class="h-6 w-6" /> Nuevo cliente / prospecto
		</h1>
		<p class="mt-1 text-sm text-muted-foreground">Al guardar podrás agregar direcciones, contactos y documentos.</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>

			<AccountFields bind:form {tab} {companyId} />

			<div class="mt-6 flex justify-end gap-2 border-t pt-4">
				<Button variant="outline" href="/dashboard/crm/cuentas">Cancelar</Button>
				<Button onclick={save} disabled={saving || !companyId}>{saving ? 'Guardando…' : 'Crear'}</Button>
			</div>
		</Card.Content>
	</Card.Root>
</div>
