<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Label } from '$lib/components/ui/label';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import * as Select from '$lib/components/ui/select';
	import { Loader2, FileSpreadsheet } from 'lucide-svelte';
	import { m } from '$lib/i18n/messages';
	import { exportDodaList, type DodaExportFileFormat, type DodaExportDateMode } from '$lib/api/dashboard/a76/general_catalogs/doda';
	import { toast } from 'svelte-sonner';

	let {
		open = $bindable(false),
		companyId
	}: {
		open: boolean;
		companyId: number | undefined;
	} = $props();

	function isoFirstDayOfMonth(): string {
		const d = new Date();
		const y = d.getFullYear();
		const mo = String(d.getMonth() + 1).padStart(2, '0');
		return `${y}-${mo}-01`;
	}

	function isoToday(): string {
		const d = new Date();
		const y = d.getFullYear();
		const mo = String(d.getMonth() + 1).padStart(2, '0');
		const day = String(d.getDate()).padStart(2, '0');
		return `${y}-${mo}-${day}`;
	}

	let dateFrom = $state(isoFirstDayOfMonth());
	let dateTo = $state(isoToday());
	let fileFormat = $state<DodaExportFileFormat>('xls');
	/** Alineado al legado: “Imprimir Fecha Juliana” = fechas/hora en archivo numérico (date_mode=raw). */
	let printJulian = $state(false);
	let busy = $state(false);

	$effect(() => {
		if (open) {
			dateFrom = isoFirstDayOfMonth();
			dateTo = isoToday();
			fileFormat = 'xls';
			printJulian = false;
		}
	});

	function dateModeValue(): DodaExportDateMode {
		return printJulian ? 'raw' : 'formatted';
	}

	async function download() {
		if (!companyId) {
			toast.error('Seleccione una compañía.');
			return;
		}
		if (!dateFrom || !dateTo) {
			toast.error(m['sidebar.doda_alta.export_excel_invalid_dates']());
			return;
		}
		busy = true;
		try {
			await exportDodaList(companyId, {
				dateFrom,
				dateTo,
				format: fileFormat,
				dateMode: dateModeValue()
			});
			open = false;
			toast.success(m['sidebar.doda_alta.export_excel_success']());
		} catch (e) {
			const msg = e instanceof Error ? e.message : String(e);
			const isEmpty =
				/no existen doda|no se encontr[óo] informaci[óo]n para exportar|no doda.*range/i.test(
					String(msg)
				);
			toast.error(
				isEmpty ? m['sidebar.doda_alta.export_no_data']() : (msg || m['sidebar.doda_alta.export_excel_error']())
			);
		} finally {
			busy = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="gap-0 overflow-hidden p-0 sm:max-w-md" showCloseButton={true}>
		<Dialog.Header class="sr-only">
			<Dialog.Title>{m['sidebar.doda_alta.export_excel_badge']()} — {m['sidebar.doda_alta.export_report_heading']()}</Dialog.Title>
		</Dialog.Header>

		<div
			class="bg-slate-900 py-2.5 pr-10 pl-4 text-center text-sm font-medium tracking-wide text-slate-50 dark:bg-slate-950"
		>
			{m['sidebar.doda_alta.export_excel_badge']()}
		</div>

		<div class="space-y-5 px-6 pb-1 pt-5">
			<h2
				class="text-foreground text-center text-sm font-semibold uppercase leading-snug tracking-wide sm:text-base"
			>
				{m['sidebar.doda_alta.export_report_heading']()}
			</h2>

			<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-3">
				<div class="space-y-2">
					<Label for="doda-exp-from" class="text-foreground/90 font-medium">{m['sidebar.doda_alta.export_fecha_inicio']()}</Label>
					<input
						id="doda-exp-from"
						type="date"
						bind:value={dateFrom}
						class="border-input bg-background text-foreground flex h-9 w-full rounded-md border px-3 text-sm shadow-sm"
					/>
				</div>
				<div class="space-y-2">
					<Label for="doda-exp-to" class="text-foreground/90 font-medium">{m['sidebar.doda_alta.export_fecha_final']()}</Label>
					<input
						id="doda-exp-to"
						type="date"
						bind:value={dateTo}
						class="border-input bg-background text-foreground flex h-9 w-full rounded-md border px-3 text-sm shadow-sm"
					/>
				</div>
			</div>

			<div class="flex flex-col items-center gap-1">
				<Button
					size="default"
					class="w-full min-w-48"
					variant="default"
					onclick={download}
					disabled={busy || !companyId}
				>
					{#if busy}
						<Loader2 class="mr-2 h-4 w-4 shrink-0 animate-spin" />
					{:else}
						<FileSpreadsheet class="mr-2 h-4 w-4 shrink-0" />
					{/if}
					{m['sidebar.doda_alta.export_report_generar']()}
				</Button>
			</div>

			<div class="flex items-start gap-2.5">
				<Checkbox id="doda-exp-julian" bind:checked={printJulian} class="mt-0.5" />
				<Label for="doda-exp-julian" class="text-muted-foreground text-sm font-normal leading-snug">
					{m['sidebar.doda_alta.export_julian_label']()}
				</Label>
			</div>

			<div class="border-t pt-3">
				<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
					<Label for="doda-exp-format" class="text-foreground/80 shrink-0 text-sm"
						>{m['sidebar.doda_alta.export_format']()}</Label
					>
					<Select.Root
						type="single"
						value={fileFormat}
						onValueChange={(v) => {
							if (v === 'csv' || v === 'xls' || v === 'txt') fileFormat = v;
						}}
					>
						<Select.Trigger id="doda-exp-format" class="w-full min-w-0 sm:max-w-[12rem]">
							.{fileFormat}
						</Select.Trigger>
						<Select.Content>
							<Select.Item value="csv">.csv (coma)</Select.Item>
							<Select.Item value="xls">.xls (tabulador, Excel)</Select.Item>
							<Select.Item value="txt">.txt (|)</Select.Item>
						</Select.Content>
					</Select.Root>
				</div>
			</div>
		</div>

		<Dialog.Footer class="border-t px-6 py-4 sm:justify-end">
			<Button type="button" variant="outline" class="min-w-24" onclick={() => (open = false)} disabled={busy}>
				{m['sidebar.doda_alta.export_cancel']()}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
