<script lang="ts">
	import { Receipt } 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 { authStore, userHasPermission } from '$lib/auth';
	import {
		issuerAPI,
		satCatalogsAPI,
		RFC_REGEX,
		type IssuerSettingsInput,
		type SatTaxRegime
	} from '$lib/api/fin';
	import { toast } from 'svelte-sonner';

	let form = $state<IssuerSettingsInput>({
		legal_name: '',
		rfc: '',
		tax_regime_id: 0,
		zip_code: ''
	});
	let taxRegimes = $state<SatTaxRegime[]>([]);
	let loading = $state(false);
	let saving = $state(false);
	/** true mientras la empresa no tenga datos capturados (el GET respondió 404). */
	let isNew = $state(true);
	let rfcError = $state('');

	const companyId = $derived(companyStore.activeCompany?.id ?? null);
	const canView = $derived(userHasPermission($authStore.user, 'fin.settings.view'));
	const canEdit = $derived(userHasPermission($authStore.user, 'fin.settings.edit'));

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

	async function load(cid: number) {
		loading = true;
		try {
			const [settings, regimes] = await Promise.all([
				issuerAPI.get(cid),
				satCatalogsAPI.taxRegimes(cid)
			]);
			taxRegimes = regimes;
			isNew = settings === null;
			if (settings) {
				form = {
					legal_name: settings.legal_name,
					rfc: settings.rfc,
					tax_regime_id: settings.tax_regime_id,
					zip_code: settings.zip_code ?? ''
				};
			}
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron cargar los datos fiscales');
		} finally {
			loading = false;
		}
	}

	function normalizedRfc(): string {
		return (form.rfc ?? '').replace(/[\s-]/g, '').toUpperCase();
	}

	async function save(event: SubmitEvent) {
		event.preventDefault();
		const cid = companyId;
		if (!cid) return;

		const rfc = normalizedRfc();
		if (!RFC_REGEX.test(rfc)) {
			rfcError = 'El RFC no tiene un formato válido (ej. XAXX010101000)';
			return;
		}
		rfcError = '';
		if (!form.tax_regime_id) {
			toast.error('Selecciona el régimen fiscal');
			return;
		}

		saving = true;
		try {
			await issuerAPI.save(
				{ ...form, rfc, zip_code: form.zip_code?.trim() ? form.zip_code.trim() : null },
				cid
			);
			isNew = false;
			toast.success('Datos fiscales guardados');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron guardar los datos fiscales');
		} finally {
			saving = false;
		}
	}

	const inputCls =
		'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';
</script>

<svelte:head>
	<title>Configuración de Facturación</title>
</svelte:head>

<div class="space-y-6">
	<div>
		<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
			<Receipt class="h-6 w-6" />
			Datos fiscales del emisor
		</h1>
		<p class="mt-1 text-sm text-muted-foreground">
			Identidad fiscal con la que la empresa emite sus comprobantes.
		</p>
	</div>

	{#if !canView}
		<Card.Root>
			<Card.Content>
				<p class="py-6 text-center text-sm text-muted-foreground">
					No tienes permiso para consultar los datos fiscales del emisor.
				</p>
			</Card.Content>
		</Card.Root>
	{:else}
		<Card.Root>
			<Card.Header>
				<Card.Title>{isNew ? 'Capturar datos fiscales' : 'Datos fiscales registrados'}</Card.Title>
				<Card.Description>
					{isNew
						? 'Esta empresa aún no tiene datos fiscales configurados.'
						: 'Actualiza la información con la que se emiten los comprobantes.'}
				</Card.Description>
			</Card.Header>
			<Card.Content>
				{#if loading}
					<p class="py-6 text-center text-sm text-muted-foreground">Cargando…</p>
				{:else}
					<form class="grid max-w-2xl gap-4 sm:grid-cols-2" onsubmit={save}>
						<label class="flex flex-col gap-1 text-sm sm:col-span-2">
							<span class="font-medium">Razón social *</span>
							<input
								class={inputCls}
								bind:value={form.legal_name}
								maxlength="255"
								required
								disabled={!canEdit}
							/>
						</label>

						<label class="flex flex-col gap-1 text-sm">
							<span class="font-medium">RFC *</span>
							<input
								class="{inputCls} font-mono uppercase"
								bind:value={form.rfc}
								maxlength="13"
								required
								disabled={!canEdit}
								oninput={() => (rfcError = '')}
							/>
							{#if rfcError}<span class="text-xs text-destructive">{rfcError}</span>{/if}
						</label>

						<label class="flex flex-col gap-1 text-sm">
							<span class="font-medium">Código postal del lugar de expedición</span>
							<input
								class={inputCls}
								bind:value={form.zip_code}
								maxlength="5"
								inputmode="numeric"
								disabled={!canEdit}
							/>
						</label>

						<label class="flex flex-col gap-1 text-sm sm:col-span-2">
							<span class="font-medium">Régimen fiscal *</span>
							<select class={inputCls} bind:value={form.tax_regime_id} required disabled={!canEdit}>
								<option value={0}>Selecciona un régimen…</option>
								{#each taxRegimes as regime (regime.id)}
									<option value={regime.id}>{regime.code} — {regime.description}</option>
								{/each}
							</select>
						</label>

						<div class="flex justify-end sm:col-span-2">
							<Button type="submit" disabled={saving || !canEdit || !companyId}>
								{saving ? 'Guardando…' : 'Guardar'}
							</Button>
						</div>
						{#if !canEdit}
							<p class="text-xs text-muted-foreground sm:col-span-2">
								Solo puedes consultar: se requiere el permiso de edición de datos fiscales.
							</p>
						{/if}
					</form>
				{/if}
			</Card.Content>
		</Card.Root>
	{/if}
</div>
