<script lang="ts">
	import { ArrowLeft, FileText } from '@lucide/svelte';
	import { goto } from '$app/navigation';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { companyStore } from '$lib/stores/company.svelte';
	import { serviceRequestsAPI, accountsAPI, suppliersAPI, contactsAPI, type ServiceRequestInput, type Account, type Supplier, type Contact } from '$lib/api/crm';
	import { SR_FORM_TABS } from '$lib/components/crm/format';
	import ServiceRequestFields from '$lib/components/crm/ServiceRequestFields.svelte';
	import { toast } from 'svelte-sonner';

	let form = $state<ServiceRequestInput>({ operation_type: 'exportacion', status: 'nueva', additional_services: [], additional_service_costs: {}, request_date: new Date().toISOString().slice(0, 10) });
	let accounts = $state<Account[]>([]);
	let suppliers = $state<Supplier[]>([]);
	let contacts = $state<Contact[]>([]);
	let tab = $state('datos');
	let saving = $state(false);

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

	$effect(() => {
		const cid = companyId;
		if (!cid) return;
		void (async () => {
			[accounts, suppliers, contacts] = await Promise.all([
				accountsAPI.list(cid), suppliersAPI.list(cid), contactsAPI.list(cid)
			]);
		})();
	});

	async function save() {
		if (!companyId) return;
		if (!form.operation_type) { toast.error('El tipo de operación es obligatorio'); return; }
		saving = true;
		try {
			const created = await serviceRequestsAPI.create(form, companyId);
			toast.success('Solicitud creada');
			await goto(`/dashboard/crm/solicitudes/${created.id}`);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo crear la solicitud');
		} finally {
			saving = false;
		}
	}
</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>
	<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><FileText class="h-6 w-6" /> Nueva solicitud de servicio</h1>

	<Card.Root>
		<Card.Content class="pt-6">
			<div class="mb-5 flex flex-wrap gap-1 border-b">
				{#each SR_FORM_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>

			<ServiceRequestFields bind:form {tab} {accounts} {contacts} {suppliers} />

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