<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { LoaderCircle } from 'lucide-svelte';
	import {
		dodaAltaLogApi,
		type DodaAltaLog,
		type DodaAltaLogUpdateDTO
	} from '$lib/api/dashboard/a76/doda-alta-log';
	import { companyStore } from '$lib/stores/company.svelte';

	let {
		open = $bindable(false),
		item = null,
		onSuccess
	}: {
		open: boolean;
		item?: DodaAltaLog | null;
		onSuccess?: () => void;
	} = $props();

	const isEdit = $derived(!!item);
	const title = $derived(isEdit ? 'Detalle de Alta DODA' : 'Nuevo Registro de Alta DODA');

	let formData = $state<DodaAltaLogUpdateDTO>({
		status: null,
		message: null,
		result_json: null
	});

	let loading = $state(false);
	let error = $state<string | null>(null);

	$effect(() => {
		if (!open) {
			error = null;
			loading = false;
			return;
		}
		if (item) {
			formData = {
				status: item.status ?? null,
				message: item.message ?? null,
				result_json: item.result_json ?? null
			};
		} else {
			formData = { status: null, message: null, result_json: null };
		}
	});

	async function handleSubmit() {
		if (loading || !item) return;
		error = null;
		loading = true;
		try {
			const company = companyStore.activeCompany;
			if (!company) throw new Error('No hay una compañía seleccionada');

			const res = await dodaAltaLogApi.update(item.id, formData, company.id);
			if (res.error) throw new Error(res.error);

			open = false;
			onSuccess?.();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Error desconocido';
		} finally {
			loading = false;
		}
	}

	async function handleDelete() {
		if (!item || !confirm('¿Está seguro de eliminar este registro de alta DODA?')) return;
		const company = companyStore.activeCompany;
		if (!company) return;
		loading = true;
		try {
			await dodaAltaLogApi.delete(item.id, company.id);
			open = false;
			onSuccess?.();
		} finally {
			loading = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-h-[90vh] overflow-y-auto sm:max-w-[700px]">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
			{#if item}
				<Dialog.Description>
					Registro #{item.id} — DODA {item.doda_id ?? '-'} — {(item.variant || 'doda').toUpperCase()}
				</Dialog.Description>
			{/if}
		</Dialog.Header>

		<div class="grid gap-6 py-4">
			{#if error}
				<div class="rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive">
					{error}
				</div>
			{/if}

			<!-- Datos de solo lectura del DODA -->
			{#if item}
				<div class="grid grid-cols-2 gap-4 rounded-lg border bg-muted/30 p-4 text-sm">
					<div>
						<p class="text-xs text-muted-foreground">No. Integración</p>
						<p class="font-medium">{item.integration_number || '-'}</p>
					</div>
					<div>
						<p class="text-xs text-muted-foreground">Responsable</p>
						<p class="font-medium">{item.responsible || '-'}</p>
					</div>
					<div>
						<p class="text-xs text-muted-foreground">Patente</p>
						<p class="font-medium">{item.patent || '-'}</p>
					</div>
					<div>
						<p class="text-xs text-muted-foreground">Aduana Despacho</p>
						<p class="font-medium">{item.dispatch_customs || '-'}</p>
					</div>
					<div>
						<p class="text-xs text-muted-foreground">Tipo Operación</p>
						<p class="font-medium">{item.operation_type || '-'}</p>
					</div>
					<div>
						<p class="text-xs text-muted-foreground">Task ID</p>
						<p class="font-mono text-xs break-all">{item.task_id || '-'}</p>
					</div>
					<div>
						<p class="text-xs text-muted-foreground">Fecha Alta</p>
						<p class="font-medium">
							{item.created_at
								? new Date(item.created_at).toLocaleString('es-MX')
								: '-'}
						</p>
					</div>
				</div>
			{/if}

			<!-- Campos editables -->
			<div class="space-y-4">
				<h4 class="text-sm font-medium text-muted-foreground leading-none">Estado</h4>
				<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
					<div class="space-y-2">
						<Label for="status">Estatus</Label>
						<Input
							id="status"
							value={formData.status ?? ''}
							oninput={(e) => (formData.status = (e.target as HTMLInputElement).value || null)}
							placeholder="pending / success / failed"
							disabled={loading}
						/>
					</div>
					<div class="space-y-2 md:col-span-2">
						<Label for="message">Mensaje</Label>
						<Input
							id="message"
							value={formData.message ?? ''}
							oninput={(e) => (formData.message = (e.target as HTMLInputElement).value || null)}
							placeholder="Mensaje del servicio externo"
							disabled={loading}
						/>
					</div>
					{#if item?.result_json}
						<div class="space-y-2 md:col-span-2">
							<Label>Resultado JSON</Label>
							<pre class="text-xs rounded-md border bg-muted p-3 overflow-auto max-h-48 whitespace-pre-wrap break-all">{(() => {
								try { return JSON.stringify(JSON.parse(item.result_json || '{}'), null, 2); }
								catch { return item.result_json || ''; }
							})()}</pre>
						</div>
					{/if}
				</div>
			</div>
		</div>

		<Dialog.Footer class="flex justify-between gap-2 pt-2">
			<Button
				type="button"
				variant="destructive"
				onclick={handleDelete}
				disabled={loading || !item}
			>
				Eliminar
			</Button>
			<div class="flex gap-2">
				<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}>
					Cancelar
				</Button>
				{#if isEdit}
					<Button type="button" onclick={handleSubmit} disabled={loading}>
						{#if loading}<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />{/if}
						Guardar
					</Button>
				{/if}
			</div>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
