<script lang="ts">
	import { FileText, Upload } from '@lucide/svelte';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { companyStore } from '$lib/stores/company.svelte';
	import { quoteSettingsAPI, type QuoteSettings } from '$lib/api/crm';
	import { toast } from 'svelte-sonner';

	const companyId = $derived(companyStore.activeCompany?.id ?? null);
	const inputCls = 'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';

	let s = $state<QuoteSettings>({});
	let logoUrl = $state<string | null>(null);
	let loading = $state(false);
	let saving = $state(false);
	let uploading = $state(false);

	$effect(() => { const cid = companyId; if (cid) void load(cid); });

	async function load(cid: number) {
		loading = true;
		try {
			s = await quoteSettingsAPI.get(cid);
			logoUrl = (await quoteSettingsAPI.logoUrl(cid).catch(() => ({ url: null }))).url;
		} catch (e) { toast.error(e instanceof Error ? e.message : 'No se pudo cargar la configuración'); }
		finally { loading = false; }
	}
	async function save() {
		if (!companyId) return;
		saving = true;
		try { s = await quoteSettingsAPI.save(companyId, s); toast.success('Configuración guardada'); }
		catch (e) { toast.error(e instanceof Error ? e.message : 'No se pudo guardar'); }
		finally { saving = false; }
	}
	async function onLogo(e: Event) {
		const file = (e.target as HTMLInputElement).files?.[0];
		if (!file || !companyId) return;
		uploading = true;
		try {
			s = await quoteSettingsAPI.uploadLogo(companyId, file);
			logoUrl = (await quoteSettingsAPI.logoUrl(companyId)).url;
			toast.success('Logo actualizado');
		} catch (err) { toast.error(err instanceof Error ? err.message : 'No se pudo subir el logo'); }
		finally { uploading = false; }
	}
</script>

<div class="space-y-6">
	<div>
		<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><FileText class="h-6 w-6" /> Formato de cotización</h1>
		<p class="mt-1 text-sm text-muted-foreground">Marca y encabezados que se imprimen en el PDF de las cotizaciones (por compañía).</p>
	</div>

	{#if !companyId}
		<Card.Root><Card.Content class="pt-6 text-sm text-muted-foreground">Selecciona una compañía activa.</Card.Content></Card.Root>
	{:else}
		<Card.Root>
			<Card.Header><Card.Title class="text-base">Logo</Card.Title></Card.Header>
			<Card.Content>
				<div class="flex flex-wrap items-center gap-4">
					{#if logoUrl}
						<img src={logoUrl} alt="Logo" class="h-16 rounded border bg-white object-contain p-1" />
					{:else}
						<div class="flex h-16 w-32 items-center justify-center rounded border border-dashed text-xs text-muted-foreground">Sin logo</div>
					{/if}
					<label class="cursor-pointer">
						<input type="file" accept="image/*" class="hidden" onchange={onLogo} />
						<span class="inline-flex items-center gap-1 rounded-md border px-3 py-2 text-sm hover:bg-muted"><Upload class="h-4 w-4" /> {uploading ? 'Subiendo…' : 'Subir logo'}</span>
					</label>
				</div>
			</Card.Content>
		</Card.Root>

		<Card.Root>
			<Card.Header><Card.Title class="text-base">Datos del emisor</Card.Title>
				<Card.Description>Aparecen en el encabezado del PDF.</Card.Description>
			</Card.Header>
			<Card.Content>
				<div class="grid gap-4 sm:grid-cols-2">
					<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Razón social (emisor)</span><input class={inputCls} bind:value={s.emitter_name} placeholder="Mi Agencia SA de CV" /></label>
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">RFC</span><input class="font-mono {inputCls}" maxlength="13" bind:value={s.emitter_rfc} /></label>
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Teléfono</span><input class={inputCls} bind:value={s.emitter_phone} /></label>
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Correo</span><input class={inputCls} bind:value={s.emitter_email} /></label>
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Sitio web</span><input class={inputCls} bind:value={s.emitter_website} /></label>
					<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Dirección</span><textarea rows="2" class={inputCls} bind:value={s.emitter_address}></textarea></label>
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Color de acento</span><input type="color" class="{inputCls} h-10 p-1" bind:value={s.accent_color} /></label>
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Prefijo de folio</span><input class={inputCls} maxlength="12" bind:value={s.quote_prefix} placeholder="COT" /></label>
				</div>
			</Card.Content>
		</Card.Root>

		<Card.Root>
			<Card.Header><Card.Title class="text-base">Textos por defecto</Card.Title></Card.Header>
			<Card.Content>
				<div class="grid gap-4">
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Condiciones comerciales (por defecto)</span><textarea rows="5" class={inputCls} bind:value={s.default_terms} placeholder="Una condición por línea…"></textarea></label>
					<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Pie de página</span><input class={inputCls} bind:value={s.footer_note} /></label>
				</div>
			</Card.Content>
		</Card.Root>

		<div class="flex justify-end"><Button onclick={save} disabled={saving || loading}>{saving ? 'Guardando…' : 'Guardar configuración'}</Button></div>
	{/if}
</div>
